简体   繁体   English

将 JSON 字符串解析为列表

[英]Parse JSON String into List

It is needed to parse JSONString into List.需要将 JSONString 解析为 List。 (List of instances) I'm trying to use JSON.NET by Newtonsoft. (实例列表)我正在尝试使用 Newtonsoft 的 JSON.NET。

I have classes:我有课:

    public class Item
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
        public string Manufactorers { get; set; }

    }

The JSON string looks something like this: JSON 字符串如下所示:

[
{     
 "Column0":23.0,
 "Column1":"Евроен",
 "Column2":"https://www.123.com",
 "Column3":"Фак"
},
{
 "Column0":24.0,
 "Column1":"Еил",
 "Column2":"https://www.123.com",
 "Column3":"Старт"
}
]

I've been trying to do something like this:我一直在尝试做这样的事情:

string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(result);
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(JSONString);

But it returns 0 and null.但它返回 0 和 null。 I have no idea, how to fix it.我不知道,如何解决它。

Also here I truy to parse Excel file.我也在这里真正解析 Excel 文件。 This code works, but after deserialization, I have just 0 and null.这段代码有效,但反序列化后,我只有 0 和 null。

var filePath = @"..\..\..\..\doc.xlsx";

using (var steam = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
   using (var reader = ExcelReaderFactory.CreateReader(steam))
   {
       var result = reader.AsDataSet().Tables["Лист1"];

       string JSONString = string.Empty;
       JSONString = JsonConvert.SerializeObject(result);

       List<Item> items = JsonConvert.DeserializeObject<List<Item>>(JSONString);

    }
}

The naming of JSON and your class does not match. JSON 的命名与您的类不匹配。 This can be fixed using JsonProperty attributes:这可以使用JsonProperty属性修复:

[JsonProperty("Column0")]
public decimal ID { get; set; }

Second, JSON deserizlizer can not deserialize string "23.0" to int when there is decimal point.其次,JSON deserizlizer 在有小数点时无法将字符串"23.0"反序列化为 int。 You can retype ID to decimal or double to make it work.您可以将 ID 重新键入为十进制或双精度以使其工作。

Little test here:这里的小测试:

public class TestClass
{
    [JsonProperty("Column0")]
    public decimal ID { get; set; }
}

Then the deserialization works without errors:然后反序列化工作没有错误:

var testClassJson = "{\"Column0\": 12.0}";
var i = JsonConvert.DeserializeObject<TestClass>(testClassJson);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM