I'm trying to read a Json string in C#, but I'm having trouble figuring out just how to parse the string into C#. Say I have the following Json string

[
    {
        "AppName": {
            "Description": "Lorem ipsum dolor sit amet",
            "Value": "1"
        },
        "AnotherAppName": {
            "Description": "consectetur adipisicing elit",
            "Value": "String"
        },
        "ThirdAppName": {
            "Description": "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua",
            "Value": "Text"
        },
        "Application": {
            "Description": "Ut enim ad minim veniam",
            "Value": "100"
        },
        "LastAppName": {
            "Description": "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat",
            "Value": "ZZZ"
        }
    }
]

I want to parse that into an arraylist or dictionary, using a format like

descriptionList["AppName"] = "Lorem ipsum dolor sit amet";
valueList["AppName"] = "1";

I've been toying around with Json.Net but the examples I've seen don't give me a clear idea of how I should do this. What's the best way to achieve this? Cant this be done like in jQuery, using a foreach statement?

推荐答案

I'm using Json.net in my project and it works great. In you case, you can do this to parse your json:

EDIT: I changed the code so it supports reading your json file (array)

要分析的代码:

void Main()
{
    var json = System.IO.File.ReadAllText(@"d:\test.json");

    var objects = JArray.Parse(json); // parse as array  
    foreach(JObject root in objects)
    {
        foreach(KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            var description = (String)app.Value["Description"];
            var value = (String)app.Value["Value"];

            Console.WriteLine(appName);
            Console.WriteLine(description);
            Console.WriteLine(value);
            Console.WriteLine("\n");
        }
    }
}

Output:

AppName
Lorem ipsum dolor sit amet
1


AnotherAppName
consectetur adipisicing elit
String


ThirdAppName
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
Text


Application
Ut enim ad minim veniam
100


LastAppName
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
ZZZ

BTW, you can use LinqPad to test your code, easier than creating a solution or project in Visual Studio I think.

Json相关问答推荐

如何在数组抖动中按值分组

我如何知道TJSONNumber是double还是double?

在Jenkins中使用ReadJSON读取json子元素

Azure Data Factory JSON输出格式问题

如何在JQ过滤器文件中使用多行?

jq 对特定键进行过滤并将值整理到单个 csv 单元格中

使用 jq 如何更改键的值?

使用动态语言jQuery:根据匹配模式提取与其他值匹配的值

Golang gin接收json数据和图片

Oracle json 对象的最后一个值不在引号中

为什么解析的字典相等而腌制的字典不相等?

阅读 JSON 正文 Firebase 云函数

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

jq:来自嵌套 JSON 的映射

如何从条带订阅响应对象中正确获取 struct 项?

json.dumps 打乱了顺序

JSON对象中的JavaScript递归搜索

使用 Codable 序列化为 JSON 时的 Swift 字符串转义

如何在spark 上将json字符串转换为数据帧

你如何在 Arrays of Arrays 上 OPENJSON