【问题标题】:How to replace property value in dynamic JSON如何替换动态 JSON 中的属性值
【发布时间】:2014-07-12 08:10:15
【问题描述】:

如何替换 JSON 字符串中的属性值?

我的json数据如下:

{
  "httpCode" : 200,
  "message" : "OK",
  "result" : {
    "furnitureItem" : {
      "id" : "f_1150426",
      "vertical" : "furniture",
      "title" : "Antique Tribal Gashgai Persian Rug",
      "description" : "Named after the Qashqa'i tribe in Persia, these nomadic rugs represent the skillful weaving styles of the tribe. Combining unique details with traditional family motifs the rugs are heavily ornamented. They often feature geometric patterns and highly developed floral designs. The colors often feature red, saffron yellow and navy. A distinguishable mark of Qashqai antique rugs is the use of flat weave.",
      "dealerReference" : "47550",
      "dibsReference" : "LU85971150426",
      "dateAdded" : "2014-05-12T15:23:26.000-04:00",
      "dateSold" : "1969-12-31T19:00:00.000-05:00",
      "releaseDate" : "2014-05-14T11:00:00.000-04:00",
      "modifiedDate" : "2014-05-12T23:48:19.000-04:00",
      "uploadType" : "USER",
      "status" : {
        "productStatus" : "UNRELEASED",
        "contactForPrice" : "N",
        "locked" : "Y",
        "posted" : "Y",
        "newListing" : "N",
        "inSaturdaySale" : "Y",
        "saveReleaseLater" : "N"
      },
      "overrideShipping" : "N",
      "pieces" : 1,
      "material" : {
        "description" : "Wool / hand Made",
        "restricted" : "N"
      },
      "customMaterial" : {
        "restricted" : "N",
        "description" : "Wool / hand Made"
      },
      "publishOptions" : {
        "dibs" : "Y",
        "featured" : "Y",
        "nydc" : "N",
        "storefront" : "Y",
        "workInProgress" : "N",
        "listedFrenchItem" : "N",
        "addText" : "N",
        "queuedForPosting" : "N",
        "rejected" : "N",
        "approved" : "N",
        "onHold" : "N",
        "deleted" : "N",
        "sold" : "N",
        "photoRepair" : "N",
        "previouslySold" : "N",
        "unpublished" : "N"
      },
      "seller" : {
        "id" : "f_8597",
        "status" : "active"
      },
      "store" : {
        "id" : 617
      },
      "classification" : {
        "style" : { },
        "countryOfOrigin" : "Iran",
        "categories" : [ "J32" ],
        "creationDate" : "Circa 1900",
        "period" : "_1900_TO_1920"
      },
      "measurement" : {
        "unit" : "IN",
        "width" : "60",
        "length" : "87",
        "weight" : { },
        "volume" : "0.0",
        "shape" : "rectangular2d"
      },
      "condition" : {
        "state" : "EXCELLENT",
        "damageLosses" : "N",
        "damageLight" : "N",
        "damageSound" : "N",
        "damageFading" : "N"
      },
      "images" : [ {
        "position" : 1,
        "status" : "PENDING",
        "thumb" : "/archivesE/upload/8597/20_14/antiquetribalgashgaipersianrug/antiquetribalGashgaipersianrug47550nazmiyal_t.jpeg",
        "small" : "/archivesE/upload/8597/20_14/antiquetribalgashgaipersianrug/antiquetribalGashgaipersianrug47550nazmiyal_l_s.jpeg",
        "medium" : "/archivesE/upload/8597/20_14/antiquetribalgashgaipersianrug/antiquetribalGashgaipersianrug47550nazmiyal_l_m.jpeg",
        "large" : "/archivesE/upload/8597/20_14/antiquetribalgashgaipersianrug/antiquetribalGashgaipersianrug47550nazmiyal_l.jpeg"
      }, {
        "position" : 2,
        "large" : ""
      }, {
        "position" : 3,
        "large" : ""
      }, {
        "position" : 4,
        "large" : ""
      }, {
        "position" : 5,
        "large" : ""
      }, {
        "position" : 6,
        "large" : ""
      }, {
        "position" : 7,
        "large" : ""
      }, {
        "position" : 8,
        "large" : ""
      }, {
        "position" : 9,
        "large" : ""
      }, {
        "position" : 10,
        "large" : ""
      } ],
      "shipping" : [ {
        "id" : 228066,
        "quoteSource" : {
          "role" : "SELLER",
          "id" : "f_8597"
        },
        "shipmentQuoteType" : "PRE_QUOTE",
        "currency" : "USD",
        "subTotal" : 0.00,
        "totalAmount" : 0.00,
        "shipmentCostIncluded" : "Y",
        "complimentaryShipping" : "Y",
        "handlingTimeDays" : 2,
        "serviceMethod" : {
          "windowMin" : 3,
          "windowMax" : 21,
          "windowUnit" : "DAY",
          "region" : "REST_OF_WORLD",
          "methodName" : "STANDARD"
        },
        "anchor" : {
          "sourceId" : "f_1150426",
          "sourceType" : "ITEM"
        },
        "amountCurrencies" : {
          "EUR" : 0.00,
          "PND" : 0.00,
          "USD" : 0.00
        },
        "invoiceItemType" : "SHIPMENT",
        "adjustmentDocumentType" : "SHIPMENT_QUOTE"
      } ],
      "pricing" : {
        "currency" : "USD",
        "lowestPrice" : 0.0,
        "amount" : 9500.0,
        "pricePerPiece" : "N",
        "negotiable" : "Y",
        "hidePrice" : "N",
        "bargain" : "N",
        "qualifyForBargain" : "Y",
        "initialPrice" : 9500,
        "initialPriceCurrencies" : {
          "EUR" : 6745.00,
          "PND" : 5510.00,
          "USD" : 9500.00
        },
        "amountCurrencies" : {
          "EUR" : 6745.00,
          "PND" : 5510.00,
          "USD" : 9500.00
        }
      },
      "returnPolicy" : { }
    }
  }
}

我想用以下内容替换“images”属性的值:

      "images": [
        {
          "position": 1,
          "thumb": "/archivesE/upload/8597/20_14/1150426/1150426_t.jpeg",
          "small": "/archivesE/upload/8597/20_14/1150426/1150426_l_s.jpeg",
          "medium": "/archivesE/upload/8597/20_14/1150426/1150426_l_m.jpeg",
          "large": "/archivesE/upload/8597/20_14/1150426/1150426_l.jpeg"
        },
        {
          "position": 2,
          "thumb": null,
          "small": null,
          "medium": null,
          "large": ""
        },
        {
          "position": 3,
          "thumb": null,
          "small": null,
          "medium": null,
          "large": ""
        },
        {
          "position": 4,
          "thumb": null,
          "small": null,
          "medium": null,
          "large": ""
        },
        {
          "position": 5,
          "thumb": null,
          "small": null,
          "medium": null,
          "large": ""
        },
        {
          "position": 6,
          "thumb": null,
          "small": null,
          "medium": null,
          "large": ""
        },
        {
          "position": 7,
          "thumb": null,
          "small": null,
          "medium": null,
          "large": ""
        },
        {
          "position": 8,
          "thumb": null,
          "small": null,
          "medium": null,
          "large": ""
        },
        {
          "position": 9,
          "thumb": null,
          "small": null,
          "medium": null,
          "large": ""
        },
        {
          "position": 10,
          "thumb": null,
          "small": null,
          "medium": null,
          "large": ""
        }
      ],

我试过正则表达式:

"images"\s*:\s*\[\s*{[\s\S]+}

更新 这是我用 JSON.NET 尝试过的: 我无法设置“图像”数组的属性值

void Main()
{
    var newValue = new[] { new Test(){Position="1"}, new Test(){Position="2"}};
    string json = File.ReadAllText("E:\\JSON.txt");
    dynamic rss = JObject.Parse(json);
    rss["result"]["furnitureItem"]["images"] = newValue;//this line throws error
    Console.WriteLine(rss.ToString());
}

public class Test
{
    public string Position {get;set;}
}

【问题讨论】:

  • 我建议使用某种 JSON 解析器而不是 RegEx。
  • 我无法使用 json 解析器,因为我不知道源 JSON 对象中有多少属性...我只确定该对象具有“图像”属性
  • 我想保持其他属性不变,只需用新值替换“图像”对象
  • 检查更新的问题
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# regex json replace json.net


【解决方案1】:

你可以使用Newtonsoft JToken来替换值,因为它支持json路径,所以更容易,下面是代码sn-p。

var parseResponse = JToken.Parse(jsonString);
var selectedPath = parseResponse.SelectToken("$.result.furnitureItem.images");
if(selectedPath!=null){
selectedPath.Replace(newValue);
}

【讨论】:

    【解决方案2】:

    试试这个:

    JObject rss = JObject.Parse(json);
    JObject furnitures = rss.SelectToken("result").SelectToken("furnitureItem");
    furnitures ["images"] = newValue;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 2017-08-31
      相关资源
      最近更新 更多