我有我需要反序列化的JSON,但我不想創建具有屬性名稱的類。將JSON反序列化爲?
這裏就是我得到的JSON:
所以"[{"id":1,"width":100,"sortable":true}, {"id":"Change","width":100,"sortable":true}]"
我怎麼能做到這一點?
感謝提前:)
我有我需要反序列化的JSON,但我不想創建具有屬性名稱的類。將JSON反序列化爲?
這裏就是我得到的JSON:
所以"[{"id":1,"width":100,"sortable":true}, {"id":"Change","width":100,"sortable":true}]"
我怎麼能做到這一點?
感謝提前:)
您可以使用JavaScriptSerializer
var list = new JavaScriptSerializer()
.Deserialize<List<Dictionary<string, object>>>(json);
var id = list[0]["id"];
或者,如果你願意,Json.Net
var list2 = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);
Json.Net還允許您使用dynamic
dynamic list = JsonConvert.DeserializeObject(json);
var wdth = list[0].width;
您可以使用json.net
我不知道這是否是你在找什麼。
string json = @"{
'CPU': 'Intel',
'PSU': '500W',
'Drives': [
'DVD read/writer'
/*(broken)*/,
'500 gigabyte hard drive',
'200 gigabype hard drive'
]
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
if (reader.Value != null)
Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
else
Console.WriteLine("Token: {0}", reader.TokenType);
}
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
string json = "[{\"id\":1,\"width\":100,\"sortable\":true}, {\"id\":\"Change\",\"width\":100,\"sortable\":true}]";
JArray array = JsonConvert.DeserializeObject(json) as JArray;
if (array != null)
{
foreach (JObject jObj in array)
Console.WriteLine("{0,10} | {1,10} | {2,10}", jObj["id"], jObj["width"], jObj["sortable"]);
}
Console.ReadKey(true);
}
}
使用Json.net,您可以直接反序列化一個匿名類:
var json = "[{\"id\":1,\"width\":100,\"sortable\":true}, \"id\":\"Change\",\"width\":100,\"sortable\":true}]";
var myExempleObject = new {id = new object(), width = 0, sortable = false};
var myArray = JsonConvert.DeserializeAnonymousType(json, new[] {myExempleObject});
我假定這裏ID可以是任何對象(如您爲例它可以是一個int或字符串),寬度必須一個int和sortable必須是一個布爾值。
您使用什麼庫進行反序列化? – ryadavilli
哪些是你使用,C# 您可以使用動態類[鏈接]語言[1] [1]:http://stackoverflow.com/questions/3142495/deserialize-json-into -c-sharp-dynamic-object – unarity
我有Newtonsoft.Json它提供了Nhibernate我猜 – harry180