如何使用NewtonSoft JsonConvert反序列化名称中带有破折号(“-”)的属性?

knsnq2tg  于 2023-03-31  发布在  其他
关注(0)|答案(3)|浏览(158)

我们有一个JSON对象,其中一个对象的名称中有一个破折号。

{
    "veg": [
        {
            "id": "3",
            "name": "Vegetables",
            "count": "25"
        },
        {
            "id": "4",
            "name": "Dal",
            "count": "2"
        },
        {
            "id": "5",
            "name": "Rice",
            "count": "8"
        },
        {
            "id": "7",
            "name": "Breads",
            "count": "6"
        },
        {
            "id": "9",
            "name": "Meals",
            "count": "3"
        },
        {
            "id": "46",
            "name": "Extras",
            "count": "10"
        }
    ],
    "non-veg": [
        {
            "id": "25",
            "name": "Starters",
            "count": "9"
        },
        {
            "id": "30",
            "name": "Gravies",
            "count": "13"
        },
        {
            "id": "50",
            "name": "Rice",
            "count": "4"
        }
    ]
}

我们如何反序列化这个json?

fdbelqdn

fdbelqdn1#

要回答如何使用NewtonSoft执行此操作的问题,您可以使用JsonProperty属性标志。

[JsonProperty(PropertyName="non-veg")]
public string nonVeg { get; set; }
33qvvth1

33qvvth12#

您可以通过使用DataContractJsonSerializer来实现这一点

[DataContract]
public class Item
{
    [DataMember(Name = "id")]
    public int Id { get; set; }
    [DataMember(Name = "name")]
    public string Name { get; set; }
    [DataMember(Name = "count")]
    public int Count { get; set; }
}

[DataContract]
public class ItemCollection
{
    [DataMember(Name = "veg")]
    public IEnumerable<Item> Vegetables { get; set; }
    [DataMember(Name = "non-veg")]
    public IEnumerable<Item> NonVegetables { get; set; }
}

现在你可以反序列化它,就像这样:

string data;

// fill the json in data variable

ItemCollection collection;
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(data)))
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ItemCollection));
    collection = (ItemCollection)serializer.ReadObject(ms);
}
5fjcxozz

5fjcxozz3#

您可以使用JObject.Parse(包含在newtonsoft中)来获取任何属性,即使它们具有特殊字符。

JObject result = JObject.Parse(json);
Console.WriteLine(result["non-veg"][0]["name"].ToString());

相关问题