We have a JSON object with one of the object having a dash in its name. Ex below.
我们有一个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"
}
]
}
How can we deserialize this json?
我们如何反序化这个json?
2 个解决方案
#1
16
You can achieve this by using DataContractJsonSerializer
您可以使用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; }
}
now you can deserialize it with something like this:
现在你可以用这样的东西反序列化它:
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);
}
#2
46
To answer the question on how to do this WITH NewtonSoft, you would use the JsonProperty property attribute flag.
要回答有关如何使用NewtonSoft执行此操作的问题,您将使用JsonProperty属性属性标志。
[JsonProperty(PropertyName="non-veg")]
public string nonVeg { get; set; }
#1
16
You can achieve this by using DataContractJsonSerializer
您可以使用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; }
}
now you can deserialize it with something like this:
现在你可以用这样的东西反序列化它:
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);
}
#2
46
To answer the question on how to do this WITH NewtonSoft, you would use the JsonProperty property attribute flag.
要回答有关如何使用NewtonSoft执行此操作的问题,您将使用JsonProperty属性属性标志。
[JsonProperty(PropertyName="non-veg")]
public string nonVeg { get; set; }