在 C# 中反序列化 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16856846/
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
Deserialize a JSON array in C#
提问by Arnab Das
I'm stuck with a tricky problem.
我遇到了一个棘手的问题。
I've a JSON string of this format:
我有一个这种格式的 JSON 字符串:
[{
"record":
{
"Name": "Komal",
"Age": 24,
"Location": "Siliguri"
}
},
{
"record":
{
"Name": "Koena",
"Age": 27,
"Location": "Barasat"
}
},
{
"record":
{
"Name": "Kanan",
"Age": 35,
"Location": "Uttarpara"
}
}
... ...
]
Fields in "record" can increase or decrease.
“记录”中的字段可以增加或减少。
So, I've made classes like this:
所以,我做了这样的课程:
public class Person
{
public string Name;
public string Age;
}
public class PersonList
{
public Person record;
}
And trying to deserialize like this:
并尝试像这样反序列化:
JavaScriptSerializer ser = new JavaScriptSerializer();
var r = ser.Deserialize<PersonList>(jsonData);
I'm doing something wrong. But unable to find. Can you please help.
我做错了什么。但是找不到。你能帮忙吗。
Thanks in advance.
提前致谢。
Update:
更新:
Actually I was getting error "Invalid JSON Primitive: ." due to I was getting the string reading a file with this code:
实际上我收到错误“无效的 JSON 原语:”。由于我正在使用以下代码读取字符串:
public static bool ReadFromFile(string path, string fileName, out string readContent)
{
bool status = true;
byte[] readBuffer = null;
try
{
// Combine the new file name with the path
string filePath = System.IO.Path.Combine(path, fileName);
readBuffer = System.IO.File.ReadAllBytes(filePath);
}
catch (Exception ex)
{
status = false;
}
readContent = (null != readBuffer) ? Utilities.GetString(readBuffer) : string.Empty;
return status;
}
Now I'm reading the file with this:
现在我正在阅读这个文件:
using (StreamReader r = new StreamReader("E:\Work\Data.json"))
{
string json = r.ReadToEnd();
result = JsonConvert.DeserializeObject<List<PersonList>>(json);
}
It's working fine.
它工作正常。
采纳答案by I4V
This should work...
这应该工作...
JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);
public class Person
{
public string Name;
public int Age;
public string Location;
}
public class Record
{
public Person record;
}
回答by Hitesh
This code is working fine for me,
这段代码对我来说很好用,
var a = serializer.Deserialize<List<Entity>>(json);
回答by RandyMohan
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }
and Remove a "{"..,
并删除一个“{”...,
strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));
DeserializeObject..,
反序列化对象..,
optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);

