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

C# 在C中搜索Json文件中的字段,c#,json,C#,Json,我有一个包含两个字段的Json文件,在搜索特定字段时遇到了一些问题 这是Json文件,我将其缩短,因为原始文件非常庞大: { "errors": { "errorCode": 0, "errorMessage": "", "errorDescription": null }, "pagination": { "recordsReturned": 250, "totalRecordsFound": 123, "currentPage":

我有一个包含两个字段的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:无效的属性标识符字符:{.Path'data.dResult[0].shape',第54行,位置11

这是我写的代码,如果你能告诉我问题出在哪里,我会很高兴的

B.我遇到的第二个问题是,我只需要选择那些形状字段值为圆形的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
        },

您可以使用以下Linq查询来提取圆形形状的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行的diff中,有一个丢失的}导致数组关闭:

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


祝你好运。如果您需要任何进一步的帮助,请告诉我。

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

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

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

问题是{shape后面的块需要一个标识符键。其他块有像seller、dResult和fancycolor这样的。看起来可能是你在编辑它的长度时把它弄糟了。嗨,我给这个问题添加了Json的另一部分,看起来shape不像你提到的那样有一个键。不确定你为什么需要重新解析。jObject[数据][dResult][0][dID]应该可以工作。那么我如何打印dID,使其匹配的形状是圆形的?我如何访问形状字段并在此时设置此条件?我现在更改了此语法的Json解析:JObject JObject=JObject.Parsejson;JToken jUser=JObject[data][dResult][0][dID];您可以使用Linq查询所有圆形对象:从jObject[data][dResult]中的r开始,其中r[shape].ToString==Round select r;谢谢,鉴于我发布的Json是我得到的源代码,它肯定存在结构问题?形状的位置与移动位置之间的主要区别是什么?移动形状:Round属性不是必需的,但它帮助我在dResult数组中排列项目。问题在于dResult数组。请注意,在原始json中,该数组中只有1个元素。应该有2个元素。基本上在第52行,在第一个形状之后:round缺少一个}来关闭数组的第一个元素。