反序列化将值转换为特定类型的JSON错误

时间:2018-09-02 19:24:16

标签: c# json serialization json.net

我有一个带有REST服务的Django后端模型,该模型创建JSON。我得到的JSON(部分)如下:

[
  {
    "id": 1,
    "username": "T1",
    "tel": "",
    "created_on": "2018-09-03T16:29:20.903315Z",
    "last_login": null,
    "hasContacts": [

    ],
    "myChanges": [

    ],
    "helpsOnChanges": [

    ],
    "shouldHelpOnChanges": [
      1
    ],
    "welldone_set": [
      {
        "id": 1,
        "created_on": "2018-09-03T16:29:20.925327Z",
        "comment": "You rock1",
        "change": 1,
        "helper": 1
      }
    ]
  },
  {
    "id": 2,
    "username": "T2",
    "tel": "",
    "created_on": "2018-09-03T16:29:20.903315Z",
    "last_login": null,
    "hasContacts": [

    ],
    "myChanges": [
      {
        "id": 1,
        "name": "Stop smoking",
        "created_on": "2018-09-03T16:29:20.923315Z",
        "change": "I want to stop smoking",
        "finished_on": null,
        "success": false,
        "helpee": 2,
        "helper": [

        ],
        "requestedHelpers": [
          1
        ],
        "welldone_set": [
          {
            "id": 1,
            "created_on": "2018-09-03T16:29:20.925327Z",
            "comment": "You rock1",
            "change": 1,
            "helper": 1
          }
        ]
      }
    ],
    "helpsOnChanges": [

    ],
    "shouldHelpOnChanges": [

    ],
    "welldone_set": [

    ]
  }
]

现在JSONConvert.Deserialize调用的显式错误是:

  

2018-09-02T18:57:13.145错误反序列化App.ViewModels.Change时出错。将值1转换为类型'App.ViewModels.User'时出错。路径“ [0] .myChanges [0] .helpee”,第1行,位置275。

这是指“ helpee”属性,其类型为user。 Django框架仅将用户的ID放在此列表中,这很有意义,因为在上面的结果之前,该JSON中已经传输了用户。

那么为什么Newtonsoft.JSON无法解决此问题?能否将此ID与具有相同ID的实际User实例相关联?

先谢谢您! 狼

编辑:为澄清我的Django后端的序列化器:

    class ChangeSerializer(serializers.ModelSerializer):
        welldone_set = WellDoneSerializer(many=True)
        class Meta:
            model = Change
            fields = ('id',
                      'name', 
                      'created_on', 
                      'change', 
                      'finished_on', 
                      'success', 
                      'helpee', 
                      'helper', 
                      'requestedHelpers', 
                      'welldone_set') 
ChangeSerializer.helpee = UserSerializer();
ChangeSerializer.helper = UserSerializer(many=True);
ChangeSerializer.requestedHelpers = UserSerializer(many=True);

如您所见,被帮助者实际上是一个对象,而不仅仅是id

编辑2:将json更新为完整

编辑3:我的解串器方法。在反序列化器行中引发了异常。

public static async Task<List<T>> getDataListFromService<T>(string queryString)
        {
            Debug.WriteLine("###Building HttpClient for " + queryString);
            HttpClient client = new HttpClient();
            Debug.WriteLine("###Building GetAsync...");
            HttpResponseMessage response = await client.GetAsync(queryString);
            Debug.WriteLine("### HTTP Get Response: " + response.ReasonPhrase);
            List<T> data = null;
            if (response.IsSuccessStatusCode)
            {
                string json = response.Content.ReadAsStringAsync().Result;
                Debug.WriteLine("### JSON REsult: " + json);
                ITraceWriter writer = new MemoryTraceWriter();
                JsonSerializerSettings settings = new JsonSerializerSettings
                {
                    TraceWriter = writer
                };
                try
                {
                    data = JsonConvert.DeserializeObject<List<T>>(json, settings);
                }
                catch (System.Exception ex)
                {
                    Debug.WriteLine("### Exception " + ex.Message);
                    Debug.WriteLine("### Trace Results: " + writer);

                }
            }
            return data;
        }

1 个答案:

答案 0 :(得分:0)

您已经知道,应该使用自定义IReferenceResolver

您在评论中问到如何使用多种类型。您可以使用here中的解析器代码来执行此操作。该链接包含完整的示例:

<script src="https://gist.github.com/carlin-q-scott/4c8a9cce734fa5b10a97.js"></script>

尽管它不使用多种类型,但很容易演示在这种情况下的用法。

例如,除了Person,我们还可以添加Cat类型:

public class Cat
{
    public string Name {get; set;}
}

然后将其添加为Person的属性:

public class Person
{
  public string Name { get; set;}
  public string PhoneNumber { get; set;}
  public Person Partner { get; set;}
  public Cat Cat { get; set;}
}

,然后将json更改为:

[
  {
     ""$id"": ""Jane Doe"",
    ""Name"": ""Jane Doe"",
    ""Cat"": {
     ""$id"": ""Johny"",
      ""Name"": ""Johny"",
    },
    ""PhoneNumber"": ""(555)555-5555"",
    ""Partner"": {
      ""$id"": ""John Doe"",
      ""Name"": ""John Doe"",
      ""PhoneNumber"": ""(555)555-5555"",
      ""Partner"": {
        ""$ref"": ""Jane Doe""
      },
      ""Cat"": {
         ""$ref"": ""Johny""
        }
    }
  },
  {
    ""$ref"": ""John Doe"",
  }
]

,它的工作原理与本fiddle中的工作相同(请注意,与其使用ReferenceResolverProvider(如链接中所示),它使用ReferenceResolver(已过时),并且因为它会在这里引起一些奇怪的错误;无论如何,您应该使用前者)。