简体   繁体   English

在C#中将单个JSON对象打印为CSV

[英]Print single JSON Object as a CSV in C#

I'm trying to print a single JObject as a CSV row 我正在尝试将单个JObject打印为CSV行

for example: 例如:

{"result": {
"id": "24095",
"hostid": "24094",
"name": "host1.fqdn.com",
"ipaddress" : "192.168.1.184"
}
}

as

id,hostid,name,ipaddress
24095,24094,host1.fqdn.com,192.168.1.184

I can easily iterate through the object with 我可以轻松地遍历对象

foreach (var item in jobj) {
   Console.Write(item.Key + ",");
}

but I end up with a , at the end of the header 但是我在标题的末尾有一个,

I tried 我试过了

for (int i = 0; i < jobj.Count; i++)...

but I'm having trouble accessing i.Key. 但我无法访问i.Key。 I'm doing something wrong here but i'm not sure what. 我在这里做错了,但是我不确定。

Any ideas on how i can print all the keys in an object as a CSV minus a , at the end? 关于如何将对象中的所有键打印为CSV减去a的任何想法,最后?

Thank you. 谢谢。

Iterate over all except the last one, then use the last one outside the block. 迭代除最后一个以外的所有对象,然后在块外使用最后一个。

for (int i = 0; i < jobj.Count-1; i++) {
    Console.Write(jobj[i].Key + ", ");
}

Console.WriteLine(jobj[jobj.Count-1].Key);

Try the following code. 请尝试以下代码。

string result = string.Empty;

foreach (var item in jobj)
{
    if (!string.IsNullOrEmpty(result))
    {
        result += ",";
    }
    result += item.Key;
}
Console.WriteLine(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM