解析JSON字符串在C# [英] Parse Json string in C#

查看:269
本文介绍了解析JSON字符串在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取C#JSON字符串,但我有麻烦找出如何去解析字符串到C#。说我有以下的JSON字符串

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"
        }
    }
]

我想分析即到一个ArrayList或字典,使用类似

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

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



我一直在玩弄Json.Net左右,但我见过的例子不给我应该怎么办?这是一个清晰的概念。什么是实现这一目标的最佳途径?不能像这样做jQuery中,使用foreach语句?

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?

推荐答案

我在我的项目中使用Json.net和它的伟大工程。在你的情况下,你可以做到这一点来分析你的JSON:

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

编辑:我改变了代码,以便它支持读取您的JSON文件(阵列)

代码解析:

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

顺便说一句,你可以使用的 LinqPad 来测试你的代码,不是建立在Visual Studio中,我认为一个解决方案或项目更容易。

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

这篇关于解析JSON字符串在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆