如何基于@ para-id将数据绑定到JSON文件

时间:2018-07-24 18:19:28

标签: c# json data-binding parameter-passing

在我的项目客户端中,向我发送此JSON字符串。

{
  "onlineRequest": {
    "CustomerCode": "AB432A",
    "MobileNumber": "75484568",
    "ProductNo": "100",
    "JsonFile": {
      "evaluation": {
        "number": [
          {
            "@para-id": "5656",
            "@new-code": "",
            "@text": "Hello America"
          },
          {
            "@para-id": "3302",
            "@new-code": "100",
            "@text": "Hello Japan"
          }
        ]
      }
    }
  }
}

此JSON包含称为JsonFile的内部JSON。现在,我需要按如下所示将此值设置为此JSON文件。

if @para-id = 5656, then @new-code = "0000" if @para-id = 3302, then @new-code = "1111"

预期输出:

{
  "onlineRequest": {
    "CustomerCode": "AB432A",
    "MobileNumber": "75484568",
    "ProductNo": "100",
    "JsonFile": {
      "evaluation": {
        "number": [
          {
            "@para-id": "5656",
            "@new-code": "0000",
            "@text": "Hello America"
          },
          {
            "@para-id": "3302",
            "@new-code": "1111",
            "@text": "Hello Japan"
          }
        ]
      }
    }
  }
}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

可以通过Newtonsoft.Json轻松完成:

var source = @"{
  ""onlineRequest"": {
    ""CustomerCode"": ""AB432A"",
    ""MobileNumber"": ""75484568"",
    ""ProductNo"": ""100"",
    ""JsonFile"": {
      ""evaluation"": {
        ""number"": [
          {
            ""@para-id"": ""5656"",
            ""@new-code"": """",
            ""@text"": ""Hello America""
          },
          {
            ""@para-id"": ""3302"",
            ""@new-code"": ""100"",
            ""@text"": ""Hello Japan""
          }
        ]
      }
    }
  }
}";
var json = JToken.Parse(source);
var dict = new Dictionary<string, string>
{
    ["5656"] = "0000",
    ["3302"] = "1000",
};

foreach (var number in json.SelectToken("onlineRequest.JsonFile.evaluation.number").ToArray())
{
    var id = (string)number["@para-id"];
    if (id != null && dict.TryGetValue(id, out var code))
    {
        number["@new-code"] = code;
    }
}