2

我所拥有的是:

string json = @"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";

如何读取字段,直到我位于“对象”,然后将整个“对象”序列化为 .NET 类型,然后继续解析?

4

3 回答 3

1

查看ServiceStack 的动态 JSON 解析

var myPoco = JsonObject.Parse(json)
    .GetUnescpaed("object")
    .FromJson<TMyPoco>();
于 2013-03-27T14:45:03.687 回答
1

定义你的类型:

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

更新

你没有说它是动态的,对于这样的解析有很多解决方案。

检查以下内容:

使用 JSON.NET 进行动态 JSON 解析

使用 C# 4.0 和动态解析 JSON

将 JSON 反序列化为 C# 动态对象?

使用动态变量解析 JSON 块

将 JSON 转换为 ExpandoObject

处理动态类型:使用dynamic, 处理动态数据,例如XMLJSON使用ExpandoObject

更新 2

使用匿名类型反序列化 JSON 数据

更新 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);
                }
            }

结果:

在此处输入图像描述

于 2013-03-27T09:29:03.123 回答
0

这适用于反序列化,我会在序列化后更新。

foreach(KeyValuePair<String,String> entry in JsonObject.Parse(json))
{

}

编辑:看起来这只适用于 json 对象。我仍然不知道如何迭代 JsonArrayObjects

于 2013-03-27T10:05:51.160 回答