使用随机密钥反序列化JSON [英] Deserialise JSON with random key
问题描述
我正在访问一个API,该API以以下格式返回JSon:
I am accessing an API which is returning JSon in the format:
{"status":1,"complete":1,"list":{"293352541":{"item_id":"293352541","fave":"0"},"247320106":{"item_id":"247320106","fave":"0"},"291842735":{"item_id":"291842735","fave":"0"} .....
我遇到的问题是 item_id标记前的数字.因为我无法在我反序列化到的对象中表示此随机整数,所以我进行反序列化的任何尝试都失败了.
The problem I am having is with the number before the item_id tag. It is breaking any attempt I make at deserialising as I cannot represent this random integer in an object that I deserialise in to.
我希望这个数字例如是单词"Item",因此它是表示封闭对象的键,但是拥有这个数字意味着我无法对JSon进行对象表示.
I would expect this number to be, for example, the word "Item", so that it is key representing the enclosed object, but having this number means I cannot make an object representation of the JSon.
所以
public class MyClass
{
public string status { get; set; }
public string complete { get; set; }
public List<MyObject> list { get; set; }
}
public class MyObject
{
public string item_id { get; set; }
public string fave { get; set; }
}
然后
var items = new JavaScriptSerializer().Deserialize<MyClass>(jsontext);
序列化,但items.list为空.
dersialises, but items.list is empty.
也是
dynamic result = JSon.Parse(jsontext);
可以工作,但是我不能很好地反序列化或访问项目列表.
works, but I cannot deserialise or access the list of items in a nice way.
有没有办法做到这一点?谢谢
Is there any way to do this? thanks
推荐答案
由于不需要反序列化为预定义的类型,因此可以使用 json.net (也可用于nuget).例如:
Because it doesn't require predefined types to deserialize into, you can do this with json.net (also available with nuget). For instance:
var jObj = JObject.Parse(data);
var sense = jObj["list"]
.Select(x => (JProperty)x)
.Select(p => new {
propName = p.Name,
itemId = p.Value["item_id"],
fave = p.Value["fave"]});
这篇关于使用随机密钥反序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!