Deserializing JSON with dynamic keys

浪子不回头ぞ 提交于 2019-12-11 17:11:33

问题


I'm quite new to JSON, and am currently learning about (de)serialization. I'm retrieving a JSON string from a webpage and trying to deserialize it into an object. Problem is, the root json key is static, but the underlying keys are dynamic and I cannot anticipate them to deserialize. Here is a mini example of the string :

{"daily":{"1337990400000":443447,"1338076800000":444693,"1338163200000":452282,"1338249600000":462189,"1338336000000":466626}

For another JSON string in my application, I was using a JavascriptSerializer and anticipating the keys using class structure. What's the best way to go about deserializing this string into an object?


回答1:


Seriously, no need to go down the dynamic route; use

var deser = new JavaScriptSerializer()
    .Deserialize<Dictionary<string, Dictionary<string, int>>>(val);
var justDaily = deser["daily"];

to get a dictionary, and then you can e.g.

foreach (string key in justDaily.Keys)
    Console.WriteLine(key + ": " + justDaily[key]);

to get the keys present and the corresponding values.




回答2:


You can use dynamic in .NET 4 or later. For example with JSON.NET I can do:

dynamic obj = JsonConvert.Deserialize<dynamic>("{x: 'hello'}");

You can then do:

var str = obj.x;

However, unsure how it will handle numeric keys. You can of course just use JObject directly itself, for example:

var obj = JObject.Parse("{'123456': 'help'}");
var str = obj["123456"];



回答3:


This is not convenient to use, because in с# can not be defined a variable starts with a number. Add prefix to keys.

Or try this:

string json = "
{ daily:[
  { key: '1337990400000', val:443447 },
  { key: '1338076800000', val:444693 },
  { key: '1338163200000', val:452282 },
  { key: '1338249600000', val:462189 },
  { key: '1338336000000', val:466626 }]
}";

public class itemClass
{
  public string key; // or int
  public int val;
}

public class items
{
  public itemClass[] daily;
}

items daily = (new JavascriptSerializer()).Deserialize<items>(json);

Then you can:

var itemValue = items.Where(x=>x.key=='1338163200000').Select(x=>x.val).FirstOrDefault();


来源:https://stackoverflow.com/questions/50149397/how-to-handle-value-has-properties-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!