Query JSON String
Is there a way to query a J开发者_开发问答SON (String) for a specific item?
ie:
String jSon = "{\"a\":{\"b\":27472483,\"c\":\"123\"}}";
such that:
Int32 bob = (Int32)getFromJSON("a.b", jSon);
// bob == 27472483
Thank you, -Theo
What you want to do here is to deserialize the JSON string into a C# object, and then access the 'b' property from there. More on that here
public T getFromJSON<T>(String sel, String jSon)
{
String[] id = sel.Split('.');
Object tmp = jSon;
for (int i = 0; i < id.Length; i++)
{
tmp = tmp.ToString().Split(new string[] { "\"" + id[i] + "\":" }, StringSplitOptions.None)[1];
}
Boolean isString = false;
if (tmp.ToString().StartsWith("\""))
{
tmp = tmp.ToString().Substring(1);
isString = true;
}
tmp = tmp.ToString().Split(new char[] { '}', ']', '"' }, StringSplitOptions.None)[0];
if (!isString && tmp.ToString().EndsWith(","))
tmp = tmp.ToString().Substring(0, tmp.ToString().Length - 1);
if (typeof(T) == typeof(Int32))
tmp = Int32.Parse(tmp.ToString());
return (T)tmp;
}
v0.7b Works!
精彩评论