【问题标题】:Json having repeated key name in different nodeJson 在不同节点中具有重复的键名
【发布时间】:2023-04-10 03:41:01
【问题描述】:

我在 json 中工作。在 json 中,数据键在单个 json 中的不同节点中重复。这是一个响应json。我怎样才能为这个 json 类创建一个序列化类。 在下面的 json 数据中重复的是不同的节点。当我尝试在线类生成器时,生成的类没有第二个数据类。我们如何解决它。

{
  "frost": {
    "response": {
      "status": {
        "message": "succe"
      },
      "totalRecords": 2,
      "data": [
        {
          "abc": "a1",
          "xyz": "te"
        },
        {
          "abc": "e5",
          "xyz": "pe"
        }
      ]
    },
    "request": {
      "method": "htl",
      "data": {
        "name": "raja",
        "partnerTypeId": "3",
        "resultType": "json"
      }
    }
  }
}

【问题讨论】:

  • 欢迎来到 StackOverflow。请与我们分享您到目前为止尝试了什么以及您在哪里卡住了。我还鼓励您访问 json2csharp.com 作为从示例 json 创建类的良好起点。

标签: c# json object serialization key


【解决方案1】:

手动执行此操作的方法是攻击每个部分。例如,response 是一个类,它有一个 status 是一个类,一个 totalRecords(一个整数)和一个 data 这是一个类实例的数组。当我完成这个练习时,我想出了这些类(总体上从上到下,但在深度方面从下到上):

public class ResponseDataItem
{
    public string abc { get; set; }
    public string xyz { get; set; }
}

public class ResponseStatus
{
    public string message { get; set; }
}

public class Response
{
    public ResponseStatus status { get; set; }
    public int totalRecords { get; set; }
    public List<ResponseDataItem> data { get; set; }

}
public class RequestData
{
    public string name { get; set; }
    public string partnerTypeId { get; set; }
    public string resultType { get; set; }
}

public class Request
{
    public string method { get; set; }
    public RequestData data { get; set; }
}

public class Overall
{
    public Response response { get; set; }
    public Request request { get; set; }
}

public class Root
{
    public Overall frost { get; set; }
}

然后,我只是将您的 JSON 反序列化为 Root 的实例:

var result = JsonConvert.DeserializeObject<Root>(theJson);

您可能希望使用 [JsonProperty] 以便拥有 C# 标准属性名称,例如:

public class ResponseDataItem
{
    [JsonProperty("abc")]
    public string Abc { get; set; }
    [JsonProperty("xyz")]
    public string Xyz { get; set; }
}

并且您可能想要重新排列内容(并且,您可能希望在某些地方使用字典),但这应该适用于您显示的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多