首页 > 解决方案 > 如何在 C# 中使用 JSON.NET 反序列化 JSON RPC 响应数组?

问题描述

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

[{"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.

标签: c#json

解决方案


你有一个数组。尝试反序列化:

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

推荐阅读