【问题标题】:Is there a way to pull a json fragment from json string in C#有没有办法从 C# 中的 json 字符串中提取 json 片段
【发布时间】:2021-05-15 18:09:04
【问题描述】:

我希望能够在 C# 中提取 json 字符串的一部分 例如,我的 json 字符串看起来像这样

{
  "accountNumber": "",  
  "Business": "Dummy Business",
   ClientId": 123,
  "location": {
    "Location#": 1,
    "LocationID": "12345",
    "Address1": "21 Fuller Road",
    "Address2": "",
    "City": "LOS ANGELES",
    "State": "CA",
    "Zipcode": "20012-1234",
    "County": "123"
   }
}

我希望能够通过 json xpath 提取数据,例如 location/Location#,它应该返回以下结果

"data": {
        "Location#": "1"
 }

同样,当我使用位置 xpath 时,它应该返回这个结果

"data": {
        "location": {
    "Location#": 1,
    "LocationID": "12345",
    "Address1": "21 Fuller Road",
    "Address2": "",
    "City": "LOS ANGELES",
    "State": "CA",
    "Zipcode": "20012-1234",
    "County": "123"
   }
 }

【问题讨论】:

标签: c# asp.net json asp.net-core


【解决方案1】:

正如 Icepickle 所说,您可以使用 Newtonsoft.Json packageJObject.SelectToken() 方法通过 JPath 表达式选择 JToken。

请参考以下示例代码:

        //required using Newtonsoft.Json.Linq;
        string jsonstr = @"{'accountNumber': '',
                        'Business': 'Dummy Business', 
                        'ClientId': 123, 
                        'location': {
                            'Location#': 1,
                            'LocationID': '12345',
                            'Address1': '21 Fuller Road',
                            'Address2': '','City': 'LOS ANGELES',
                            'State': 'CA',
                            'Zipcode': '20012-1234',
                            'County': '123'   
                            }
                        }";
        JObject o = JObject.Parse(jsonstr);
        JToken acme = o.SelectToken("$.location");

        string result = @"{'data': { 'location':"+ acme.ToString() + "} }";

结果如下:

更多详情,请查看Querying JSON with complex JSON Path

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多