JSON DeserializeObject无法将当前JSON数组(例如[1,2,3])反序列化为type

时间:2019-07-18 22:06:17

标签: json serialization json.net

当我使用Newtonsoft JSON.net将JSON反序列化到类中时,出现此错误。可能是什么原因造成的?当然,我缺少明显的东西。

  

无法将当前JSON数组(例如[1,2,3])反序列化为类型

这是我的JSON:

[
  {
"AgreementUID": "a8ea9f59-82f3-4799-b684-06a2cd95d9a1",
"ProjectUID": "851D12CE-7DC3-E511-9C58-F0DEF17C096F",
"year": "2016",
"data": [
  {
    "month": 1,
    "B": "4",
    "P": "1",
    "F": "1"
  },
  {
    "month": 2,
    "B": "",
    "P": "",
    "F": ""
  }
  ]
 }
]

这是我的班级:

public class AgreementBreakdownObject
{
    public string AgreementUID { get; set; }
    public string ProjectUID { get; set; }
    public string year { get; set; }
    public List<AgreementBreakdownDataObject> data { get; set; }
}
public class AgreementBreakdownDataObject
{
    public int month { get; set; }
    public string B { get; set; }
    public string P { get; set; }
    public string F { get; set; }
}

我确实像这样反序列化:

string jsonData = hData.Value;
var data = JsonConvert.DeserializeObject<List<AgreementBreakdownObject>> (jsonData);

请在这里提出我的错误。谢谢

1 个答案:

答案 0 :(得分:0)

如果json在C#字符串内,则需要对引号进行转义。下面的示例:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace ConsoleApp3
{
    public class AgreementBreakdownObject
    {
        public string AgreementUID { get; set; }
        public string ProjectUID { get; set; }
        public string year { get; set; }
        public List<AgreementBreakdownDataObject> data { get; set; }
    }
    public class AgreementBreakdownDataObject
    {
        public int month { get; set; }
        public string B { get; set; }
        public string P { get; set; }
        public string F { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var data = JsonConvert.DeserializeObject<List<AgreementBreakdownObject>>(@"[
  {
""AgreementUID"": ""a8ea9f59-82f3-4799-b684-06a2cd95d9a1"",
""ProjectUID"": ""851D12CE-7DC3-E511-9C58-F0DEF17C096F"",
""year"": ""2016"",
""data"": [
  {
    ""month"": 1,
    ""B"": ""4"",
    ""P"": ""1"",
    ""F"": ""1""
  },
  {
    ""month"": 2,
    ""B"": """",
    ""P"": """",
    ""F"": """"
  }
  ]
 }
]");
            Console.WriteLine(JsonConvert.SerializeObject(data, Formatting.Indented));

            Console.ReadKey();
        }
    }
}

相关摘录from MSDN

  

当字符串文本包含反斜杠字符(例如在文件路径中)时,请使用逐字字符串以方便使用并提高可读性。由于逐字字符串会将换行符保留为字符串文本的一部分,因此可以将其用于初始化多行字符串。使用双引号将引号嵌入到逐字字符串中。