首页 > 解决方案 > In c# json object has only 1 data and json.Count is not working

问题描述

While extracting Json, I get as result either :

{"uri":"./factory/languages/de-de","name":"de-de"}

or

[{
        "uri": "./factory/languages/de-de",
        "name": "de-de"
    }, {
        "uri": "./factory/languages/en-us",
        "name": "en-us"
    }, {
        "uri": "./factory/languages/he-il",
        "name": "he-il"
    }
]

The json object returns one item or a List. When the object consists of only single data then json.Count property is not working.

{
   // Parse the response body.
   //Make sure to add a reference to System.Net.Http.Formatting.dll
   var dataObjects = response.Content.ReadAsStringAsync().Result;  
   Console.WriteLine("Status : {0}\nReason : ({1})", (int)response.StatusCode, response.StatusCode);
   Console.WriteLine("Data from server :\n"+dataObjects);
   dynamic json = JValue.Parse(dataObjects);
   Console.WriteLine("\nData extracted by parsing in JSON format");
   //Console.WriteLine(json.Count);
   for(int i = 0; i<json.Count;i++) // error here
   {
      Console.WriteLine("\n"+(i+1)+".");
      Console.WriteLine("name :"+json[i].name);
      Console.WriteLine("uri :"+json[i].uri);
   }
}

It is not entering the for loop. But if I print directly json.name it's working.

I want to write code that works for both single data and multiple data.

标签: c#json

解决方案


临时解决方案:

我得到了一些解决方案。我在第一个索引处检查了“[”的返回字符串,如果它不包含,那么我将分别在字符串的开头和结尾添加“[”和“]”。代码片段:

 string dataObjects = response.Content.ReadAsStringAsync().Result;  
 //Make sure to add a reference to System.Net.Http.Formatting.dll
 Console.WriteLine("Status : {0}\nReason : ({1})",
                        (int)response.StatusCode, response.StatusCode);
Console.WriteLine("Data from server :\n"+dataObjects);
dynamic json;
if(dataObjects[0]!='[')
{
    json = JValue.Parse("["+dataObjects+"]"); 
}
else
{
    json = JValue.Parse(dataObjects);
}

Console.WriteLine("\nData extracted by parsing in JSON format");
Console.WriteLine(json.Count);
for(int i = 0; i<json.Count;i++)
{
    Console.WriteLine("\n"+(i+1)+".");
    Console.WriteLine("name :"+json[i].name);
    Console.WriteLine("uri :"+json[i].uri);
}

推荐阅读