如何在C#中使用JSON.NET反序列化JSON RPC响应数组?

时间:2019-01-03 15:42:35

标签: c# json

我有一个如下所示的JSON字符串response

[{"result":"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f","error":null,"id":"0"},
{"result":"00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048","error":null,"id":"1"},
{"result":"000000006a625f06636b8bb6ac7b960a8d03705d1ace08b1a19da3fdcc99ddbd","error":null,"id":"2"},
{"result":"0000000082b5015589a3fdf2d4baff403e6f0be035a5d9742c1cae6295464449","error":null,"id":"3"}]

我想将其反序列化为仅具有result属性的字符串数组,并将其返回。

我创建了此类以将每个对象保存在数组中,但是不确定如何反序列化它。

public class RPCResponse<T>
{
    public T result { get; set; }
    public string error { get; set; }
    public string id { get; set; }
}

我尝试了var hashes = JsonConvert.DeserializeObject<RPCResponse<string>>(response);,但遇到了错误

Newtonsoft.Json.JsonSerializationException
  HResult=0x80131500
  Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RPCResponse`1[System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

2 个答案:

答案 0 :(得分:3)

您有很多。尝试使用以下方法反序列化:

JsonConvert.DeserializeObject<RPCResponse<string>[]>(response);

答案 1 :(得分:-3)

我认为您应该从json中删除[]符号。您的json应该看起来像这样:

{"result":"gg","error":null,"id":"0"},
{"result":"gg","error":null,"id":"1"}