C# 将 JSON 反序列化为字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14640028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deserializing JSON into string array
提问by Chris
I just started dabbling with C#, and I've been banging my head over JSON deserialization for a while now. I'm using Newtonsoft.Json library. I'm expecting just a json response of an array of dictionaries as such
我刚刚开始涉足 C#,并且我一直在思考 JSON 反序列化有一段时间了。我正在使用 Newtonsoft.Json 库。我只期待像这样的字典数组的 json 响应
[{"id":"669","content":" testing","comments":"","ups":"0","downs":"0"}, {"id":"482","content":" test2","comments":"","ups":"0","downs":"0"}]
Right now I have: (note: download is just a string holding the json string)
现在我有:(注意:下载只是一个包含 json 字符串的字符串)
string[] arr = JsonConvert.DeserializeObject<string[]>(download);
I've tried many different ways of doing this, each failed. Is there a standard way for parsing json of this type?
我尝试了很多不同的方法来做到这一点,每一种都失败了。是否有解析这种类型的 json 的标准方法?
采纳答案by Despertar
You have an array of objectsnot strings. Create a class that maps the properties and deserialize into that,
你有一个对象数组而不是字符串。创建一个映射属性并反序列化为该属性的类,
public class MyClass {
public string id { get; set; }
public string content { get; set; }
public string ups { get; set; }
public string downs { get; set; }
}
MyClass[] result = JsonConvert.DeserializeObject<MyClass[]>(download);
There are only a few basic types in JSON, but it is helpful to learn and recognize them. Objects, Arrays, strings, etc. http://www.json.org/and http://www.w3schools.com/json/default.aspare good resources to get started. For example a string array in JSON would look like,
JSON 中只有几个基本类型,但是学习和识别它们是有帮助的。对象、数组、字符串等。http://www.json.org/和http://www.w3schools.com/json/default.asp是很好的入门资源。例如,JSON 中的字符串数组如下所示,
["One", "Two", "Three"]
回答by Rahul
I implement this and hope this is helpful all.
我实现了这个,希望这对所有人都有帮助。
var jsonResponse =
[{"Id":2,"Name":"Watch"},{"Id":3,"Name":"TV"},{"Id":4,"Name":""}]
var items = JsonConvert.DeserializeObject<List<MyClass>>(jsonResponse);
where MyClass is the entity
其中 MyClass 是实体
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
}