【问题标题】:How to parse JSON to Object which has a property如何将 JSON 解析为具有属性的对象
【发布时间】:2017-07-28 09:44:34
【问题描述】:

我需要从服务器返回的数据将带有“数据”属性,而JsonConvert.SerializeObject() 的返回则没有。如何转换?

发件人:

{
    "name": "Tiger Nixon",
    "position": "System Architect",
    "salary": "$320,800",
    "start_date": "2011/04/25",
    "office": "Edinburgh",
    "extn": "5421"
}

收件人:

{
    "data": [{
        "name": "Tiger Nixon",
        "position": "System Architect",
        "salary": "$320,800",
        "start_date": "2011/04/25",
        "office": "Edinburgh",
        "extn": "5421"
    }]
}

在 VB.net 中(也可以在 C# 中,我会转换)。

【问题讨论】:

标签: c# json vb.net json.net


【解决方案1】:

如果您从模型类的实例开始,您可以将其包装在匿名对象中并对其进行序列化:

Dim anon = New With {.data = New List(Of Model) From {model}}
Dim json As String = JsonConvert.SerializeObject(anon, Formatting.Indented)

小提琴:https://dotnetfiddle.net/45RtrC


如果您从 JSON 字符串开始,您可以使用 JObject 对其进行转换:

Dim jo As JObject = JObject.Parse(json)
jo = New JObject(New JProperty("data", New JArray(jo)))
json = jo.ToString()

小提琴:https://dotnetfiddle.net/ezP6QR

【讨论】:

    【解决方案2】:

    你可以把它解析成一个数组,然后像这样序列化它

    Model[] data = JObject.Parse(json_string).ToObject<Model[]>();
    

    考虑到您有一个与 JSON 字符串关联的模型

    public class Model
    {
        public string name { get; set; }
        public string position { get; set; }
        public string salary { get; set; }
        public string start_date { get; set; }
        public string office { get; set; }
        public string extn { get; set; }
    }
    

    【讨论】:

    • 仍未获得“名称”属性。现在它看起来像这样: [{"status":2,"transactionId":12345,"creditCardNumber":"1234324324","supplier":"Office Depot","createdAt":"2008-12-28T00:00: 00","金额":500.0}]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多