【问题标题】:Approach for parsing json string with different type of objects解析具有不同类型对象的json字符串的方法
【发布时间】:2013-08-13 19:14:04
【问题描述】:

我有以下 json 字符串

{
    "serverTime": "2013-08-12 02:45:55,558",
    "data": [{
        "key1": 1,
        "result": {
            "sample1": [""],
            "sample2": "test2"
        }
    },{
        "key1": 1,
        "result": {
            "sample3": [""],
            "sample4": "test2"
        }
    }]
}

使用JSONTOC#

生成以下类。

public class Result 
{
    public List<string> sample1 { get; set; }
    public string sample2 { get; set; }
    public List<string> sample3 { get; set; }
    public string sample4 { get; set; } 
} 

public class Datum 
{
    public int key1 { get; set; }
    public Result result { get; set; } 
}

public class RootObject 
{
    public string serverTime { get; set; }
    public List<Datum> data { get; set; } 
}

正如您所见,该工具已生成具有所有可能属性的 Result 类。

我正在尝试以下方法来解析 json

public class Response<T>
{
    public Date serverTime;
    public ResponseData<T>[] data;
}

public class ResponseDataBase
{
    public int key1;
}

public class ResponseData<T> : ResponseDataBase
{
    public T result;
}

这里可以T关注两个类

Class Result1
{
   public List<string> sample1 { get; set; }
   public string sample2 { get; set; }
}

Class Result2
{
    public List<string> sample3 { get; set; }
    public string sample4 { get; set; }
}

我有这些类声明作为参考,类定义可以完全不同。

** 我如何通过指定 Result 类型来解析这个 json。** 我正在使用 JSONFx.net 反序列化回对象。

谢谢

【问题讨论】:

  • 在 json.net 中,我们在这种情况下使用转换器。也许你想让你的问题更清楚。

标签: c# json parsing jsonfx


【解决方案1】:

从您的 JSON 数据生成的类:

public class Result
{
    public List<string> sample1 { get; set; }
    public string sample2 { get; set; }
}

public class Datum
{
    public int key { get; set; }
    public Result result { get; set; }
}

    public class RootObject
    {
    public string serverTime { get; set; }
    public List<Datum> data { get; set; }
}

使用 Newtonsoft.Json dll 反序列化 JSON 数据,例如:

var obj = JsonConvert.DeserializeObject<RootObject>("yourjsonstring");

然后你可以使用像这样的 obj 属性:

var date = DateTime.Parse(obj.serverTime);

等等。

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 2023-03-07
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    相关资源
    最近更新 更多