JsonConvert DeserializeObject找不到int成员

时间:2017-01-30 15:10:10

标签: c# json serialization json.net

我有一个奇怪的情况,我的其他类正确地反序列化,但是这个具有三个int值的类没有正确地反序列化。使用跟踪编写器设置,我看到Json.Net报告它找不到成员,但我不确定原因。

类别:

public class BroadcastMemoryResponse : BaseResponse
{
    public int FreeMemory { get; set; }

    [JsonProperty("Malloc_Count")]
    public int MallocCount { get; set; }

    [JsonProperty("Free_Count")]
    public int FreeCount { get; set; }
}

JSON:

{
  "ID": 100,
  "Service": "BroadcastMemory",
  "FreeMemory: ": 50508,
  "Malloc_Count: ": 10050409,
  "Free_Count: ": 10049533,
  "Status": "Success"
}

请注意,IDServiceStatus字段位于BaseResponse类中,并且这些字段已成功反序列化(ID为int且正确反序列化)。我使用JsonProperties在映射到C#时删除JSON中的下划线。类和属性都是公共的,getter / setter是公共的,因此不确定问题是什么。?

测试反序列化代码:

ITraceWriter traceWriter = new MemoryTraceWriter();
var settings = new JsonSerializerSettings { TraceWriter = traceWriter };
string str = "{\"ID\":100,\"Service\":\"BroadcastMemory\",\"FreeMemory: \":50508,\"Malloc_Count: \":10050409,\"Free_Count: \":10049533,\"Status\":\"Success\"}";
var deserializedObj = JsonConvert.DeserializeObject<BroadcastMemoryResponse>(str, settings);

跟踪编写器输出:

2017-01-30T09:49:46.807 Info Started deserializing TcpClient.Core.Model.BroadcastMemoryResponse. Path 'ID', line 1, position 6.
2017-01-30T09:49:46.836 Verbose Could not find member 'FreeMemory: ' on TcpClient.Core.Model.BroadcastMemoryResponse. Path '['FreeMemory: ']', line 1, position 51.
2017-01-30T09:49:46.838 Verbose Could not find member 'Malloc_Count: ' on TcpClient.Core.Model.BroadcastMemoryResponse. Path '['Malloc_Count: ']', line 1, position 74.
2017-01-30T09:49:46.838 Verbose Could not find member 'Free_Count: ' on TcpClient.Core.Model.BroadcastMemoryResponse. Path '['Free_Count: ']', line 1, position 98.
2017-01-30T09:49:46.840 Info Finished deserializing TcpClient.Core.Model.BroadcastMemoryResponse. Path '', line 1, position 126.
2017-01-30T09:49:46.841 Verbose Deserialized JSON: 
{
  "ID": 100,
  "Service": "BroadcastMemory",
  "FreeMemory: ": 50508,
  "Malloc_Count: ": 10050409,
  "Free_Count: ": 10049533,
  "Status": "Success"
}

1 个答案:

答案 0 :(得分:3)

问题在于,在您的Json中,您的属性名称格式不正确(例如"FreeMemory: "而不是"FreeMemory")。这一行:

"{ … \"FreeMemory: \":50508,\"Malloc_Count: \":10050409,\"Free_Count: \":10049533, … }"

应该是:

"{ … \"FreeMemory\":50508,\"Malloc_Count\":10050409,\"Free_Count\":10049533, … }"

或者,如果您实际上无法控制消息,则只需更改JsonProperty属性:

[JsonProperty("FreeMemory: ")]
public int FreeMemory { get; set; }

[JsonProperty("Malloc_Count: ")]
public int MallocCount { get; set; }

[JsonProperty("Free_Count: ")]
public int FreeCount { get; set; }