我所拥有的是:
string json = @"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";
如何读取字段,直到我位于“对象”,然后将整个“对象”序列化为 .NET 类型,然后继续解析?
我所拥有的是:
string json = @"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";
如何读取字段,直到我位于“对象”,然后将整个“对象”序列化为 .NET 类型,然后继续解析?
var myPoco = JsonObject.Parse(json)
.GetUnescpaed("object")
.FromJson<TMyPoco>();
定义你的类型:
public class Object
{
public int t { get; set; }
public string whatever { get; set; }
public string str { get; set; }
}
public class RootObject
{
public int number { get; set; }
public Object object { get; set; }
}
然后反序列化它:
string json = @"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";
var deserialized = JsonConvert.DeserializeObject<RootObject>(json);
//do what you want
更新
你没有说它是动态的,对于这样的解析有很多解决方案。
检查以下内容:
处理动态类型:使用dynamic
, 处理动态数据,例如XML或JSON使用ExpandoObject
。
更新 2
更新 3
这对你有用吗:
string json = "{\"number\": 3, \"object\" : { \"t\" : 3, \"whatever\" : \"hi\", \"str\": \"test\"}}";
var deserialized = SimpleJson.DeserializeObject<IDictionary<string, object>>(json);
var yourObject = deserialized["object"] as IDictionary<string, object>;
if (yourObject != null)
{
var tValue = yourObject.GetValue("t");
var whateverValue = yourObject.GetValue("whatever");
var strValue = yourObject.GetValue("str");
}
public static object GetValue(this IDictionary<string,object> yourObject, string propertyName)
{
return yourObject.FirstOrDefault(p => p.Key == propertyName).Value;
}
最后结果:
或者改成以下
if (yourObject != null)
{
foreach (string key in yourObject.Keys)
{
var myValue = yourObject.GetValue(key);
}
}
更新 4 - 服务堆栈
string json = "{\"number\": 3, \"object\" : { \"t\" : 3, \"whatever\" : \"hi\", \"str\": \"test\"}}";
var deserialized = JsonObject.Parse(json);
var yourObject = deserialized.Get<IDictionary<string, object>>("object");
if (yourObject != null)
{
foreach (string key in yourObject.Keys)
{
var myValue = yourObject.GetValue(key);
}
}
结果:
这适用于反序列化,我会在序列化后更新。
foreach(KeyValuePair<String,String> entry in JsonObject.Parse(json))
{
}
编辑:看起来这只适用于 json 对象。我仍然不知道如何迭代 JsonArrayObjects