c# - 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.
解决方案
临时解决方案:
我得到了一些解决方案。我在第一个索引处检查了“[”的返回字符串,如果它不包含,那么我将分别在字符串的开头和结尾添加“[”和“]”。代码片段:
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);
}
推荐阅读
- python - Why does Python ignore source files in favor of pyc files sometimes?
- arm - 如何访问 Arm MBED 中的 X-Nucleo-NFC05A1 扩展板?
- r - ggplot boxplot:异常值太多?
- angular - 构建 Angular 应用程序时出错需要一个表达式,但看到了 AST
- closures - 如何在闭包中返回 single.deferred
- javascript - 为什么我的菜单栏在 wordpress 中没有像在普通 html 文件中那样收缩时正确收缩?
- android - 如何在 RxJava2/RxKotlin 中正确组合包含点击事件和值的 Observables
- php - 从 MySQL 结果和 PHP 为 D3.js 树创建分层 JSON?
- php - 巨大的 php 文件有多糟糕?
- c - 我可以从 GDataOutputStream 获取或转换到底层 GOutputStream 吗?