开发者

Best way to handle .NET json [1,2,"three"]

-edit- Maybe there is a solution by using attributes?

I found the weirdest json. It looks like the string below. The only way i can think of to handle it is to use an object array. I never seen ints and strings mixed in an array below.

I am then forced to typecast. Is there a better way to get the ints and string?

NOTE: The first array can have 0 to 20 elements. The array inside of it ALWAYS has 3 with the f开发者_C百科irst two being ints and the 3rd a string. Maybe i can use this knowledge to my advantage?

{
 var ser = new JavaScriptSerializer();
 var o = ser.Deserialize<RootObj>(@"{""resources"": [[123,567,""<div ...""]]}");
 var o2 = o.resources[0];
 var v = (int)o2[1];
 var sz = (string)o2[2];
}
class RootObj {
 public object[][] resources;
}


Sounds like a bit of LINQ would come in handy here. Given your deserialised object o, you'd want something like the following.

var result = o.Select(c => new
                      {
                          v1 = (int)c[0],
                          v2 = (int)c[1],
                          sz = (string)c[2],
                      });

Note that the new { ... } construct creates an object of anoynomous type, you can use a struct if that's more suitable perhaps.

Still, you haven't given any real context, so the best solution may in fact be to do nothing and leave the deserialised result as a weakly-typed object array... You can always cast the values to specific types when you need to use them explicitly later.


Ignore it because using an object is no bad at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜