首页 > 解决方案 > 如何更新 JSON 字段

问题描述

我正在尝试更新 JSON 响应中的特定字段,但是我能够解析 JSON,但我无法更新字段值。

通过 JSON 响应解析并尝试使用

Operands_parse.SelectToken("FieldValue").Replace("1234,5678");

但是当替换正在改变不应该发生的响应格式时

JObject Operands_parse = (JObject)Operands[0]; Operands_parse.SelectToken("FieldValue").Replace("1234,5678");

下面是 JSON 片段:

  "Predicate": {
    "Field": null,
    "FieldValue": null,
    "FilterOperator": "Equals",
    "Operands": [
      {
        "Field": {
          "Name": "Participant.IsPrimary",
          "Alias": "Participant Is Primary",
          "ValueInput": "UserName",
          "FieldType": "Boolean",
          "SortProxyName": "IsPrimary",
          "PrismFieldName": "IsPrimaryFA",
          "PrismDisplayFieldName": null,
          "FieldValue": null,
          "IsCustom": false,
          "DependentField": null,
          "Disabled": false,
          "PlannedForDeprecation": false
        },
        "FieldValue": [
          "true"
        ]

输出:

"FieldValue":
      "1234,
       5678", 

预期的:

 "FieldValue": [
      "1234",
      "5678"
    ],

标签: c#json

解决方案


将特定字段转换为 JArray 后,事情就开始了,我可以从中更新值。

  string[] CRs ;
  CRs = new string[2] {"1234","5678"};  

  JObject Operands_parse = (JObject)Operands[0];
  JToken FieldValue_t;
  Operands_parse.TryGetValue("FieldValue", out FieldValue_t);

    JArray item = (JArray)FieldValue_t;
/*Removed old values*/
    item.RemoveAt(0);
    item.RemoveAt(1);
/*Added New Values*/
    item.Add(items_no[0]);
    item.Add(items_no[1]);

`

  "Predicate": {
    "Field": null,
    "FieldValue": null,
    "FilterOperator": "Equals",
    "Operands": [
      {
        "Field": {
          "Name": "ChangeRequestParticipant.IsPrimary",
          "Alias": "Participant Is Primary",
          "ValueInput": "UserName",
          "FieldType": "Boolean",
          "SortProxyName": "ChangeRequestParticipant.IsPrimary",
          "PrismFieldName": "IsPrimaryFA",
          "PrismDisplayFieldName": null,
          "FieldValue": null,
          "IsCustom": false,
          "DependentField": null,
          "Disabled": false,
          "PlannedForDeprecation": false
        },
        "FieldValue": [
          "1234",
          "5678"
        ],`

从此链接参考


推荐阅读