在C#中的Json文件中搜索字段

时间:2018-11-20 18:47:57

标签: c# json

我有一个包含几个字段的Json文件,但是在搜索特定字段时遇到一些问题。

这是Json文件(由于原始文件很大,因此我将其缩短了):

{
  "errors": {
    "errorCode": 0,
    "errorMessage": "",
    "errorDescription": null
  },
  "pagination": {
    "recordsReturned": 250,
    "totalRecordsFound": 123,
    "currentPage": 1,
    "recordsPerPage": 250
  },
  "data": {
    "totalDCount": 1713,
    "totalValue": "50",
    "totalCarats": 60,
    "averagePricePerCarat": 21,
    "averageDiscount": -0.29,
    "dResult": [
      {
        "color": "H",
        "dID": 4693,
        "fancyColor": {
          "dominantColor": null,
          "secondaryColor": null,
          "overtones": null,
          "intensity": null,
          "color1": null,
          "color2": null
        },
        "seller": {
          "accountID": 124,
          "companyName": "",
          "companyCode": " ",
          "founded": "",
          "address": null,
          "telephone": " ",
          "fax": null,
          "email": null,
          "contactPrimaryName": "value",
          "city": null,
          "state": null,
          "country": "USA",
          "address1": null,
          "address2": null,
          "skypeName": null,
          "primarySupplierBadge": true,
          "ratingPercent": 1.0,
          "totalRating": 1.0,
          "relatedAccounts": null
        },

          "shape": "Round",
          {
        "color": "H",
        "dID": 46,
        "fancyColor": {
          "dominantColor": null,
          "secondaryColor": null,
          "overtones": null,
          "intensity": null,
          "color1": null,
          "color2": null
        },
        "seller": {
          "accountID": 124,
          "companyName": "",
          "companyCode": " ",
          "founded": "",
          "address": null,
          "telephone": " ",
          "fax": null,
          "email": null,
          "contactPrimaryName": "value",
          "city": null,
          "state": null,
          "country": "USA",
          "address1": null,
          "address2": null,
          "skypeName": null,
          "primarySupplierBadge": true,
          "ratingPercent": 1.0,
          "totalRating": 1.0,
          "relatedAccounts": null
        },

          "shape": "Round" 

      }
    ]
  }
}

我编写了一个代码,应在“ dResult”下搜索“ dId”字段值。不幸的是,出现此错误(我正在使用Newtonsoft.Json解析器):

“ Newtonsoft.Json.JsonReaderException:无效的属性标识符字符:{。路径'data.dResult [0] .shape',第54行,位置11。”

A。这是我编写的代码,如果您能告诉我问题出在哪里,我会很高兴?

我遇到的第二个问题是,我只需要选择那些具有“ shape”字段值作为“ Round”的值的“ dID”,我就没有办法做到这一点,因为我需要遇到“ dId”字段时,去寻找另一个字段。

  class Program
{
    static void Main(string[] args)
    {
        string filepath = "../../json1.json";
        string result = string.Empty;
        string str = string.Empty;
        using (StreamReader r = new StreamReader(filepath))
        {


            var json = r.ReadToEnd();


            JObject jObject = JObject.Parse(json);
            JToken jUser = jObject["data"];
            string jsonString = jUser.ToString();
            JObject jObject1 = JObject.Parse(jsonString);

            JToken jUser2 = jObject1["dResult"];

            string jsonString2 = jUser2.ToString();
            JObject jObject2 = JObject.Parse(jsonString2);


            foreach (var item in jObject2.Properties())
                {

                if (item.Name == "dID")
                {
                    str = item.Value.ToString();

                            result = result + " " + str;
                }

        }

    }

        Console.WriteLine(result);

    }
}

我在这里收到的评论的引用(另一个Json部分,在“ dResult”下):

, {
        "dID": 281242,
        "seller": {
            "accountID": 21321,
            "companyName": "RA",
            "companyCode": "001",
            "founded": "000",
            "address": null,
            "telephone": "999",
            "fax": null,
            "email": null,
            "contactPrimaryName": "name",
            "city": null,
            "state": null,
            "country": "USA",
            "address1": null,
            "address2": null,
            "skypeName": null,
            "primarySupplierBadge": true,
            "ratingPercent": 1.0,
            "totalRating": 1.0,
            "relatedAccounts": null
        },
        "shape": "Round",
        "size": 0.010,
        "color": "K",
        "fancyColor": {
            "dominantColor": null,
            "secondaryColor": null,
            "overtones": null,
            "intensity": null,
            "color1": null,
            "color2": null
        },

2 个答案:

答案 0 :(得分:0)

您可以使用以下Linq查询为Round形状提取dID值。但是,JSON格式不正确。

var jsonStr = File.ReadAllText(Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop), 
    "example-json.json"));

var parsed = JObject.Parse(jsonStr);

var dIdList = parsed["data"]["dResult"]
    .Where(x => x.Value<String>("shape").Equals("round", StringComparison.InvariantCultureIgnoreCase))
    .Select(x => x.Value<Int32>("dID"))
    .ToList();

这是重新格式化的JSON(请注意第52-53行的差异),缺少}导致数组关闭:

enter image description here

更正JSON后,通过添加此}并运行上面的Linq查询,它将返回以下结果:

enter image description here

祝你好运。让我知道您是否需要任何进一步的帮助。

答案 1 :(得分:0)

一旦修复了格式不正确的json数据,就可以使用linq查找圆形对象:

var searchResults = from r in jObject["data"]["dResult"]
                    where r["shape"].ToString() == "Round"
                    select r;

foreach (var r in searchResults)
{
    Console.WriteLine(r["dID"]);
}