在 C# 中解析 Json 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12676746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:04:47  来源:igfitidea点击:

Parse Json string in C#

c#jsonjson.net

提问by desto

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

我正在尝试在 C# 中读取 Json 字符串,但我无法弄清楚如何将字符串解析为 C#。假设我有以下 Json 字符串

[
    {
        "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?

我一直在玩弄 Json.Net,但我看到的例子并没有让我清楚地知道我应该如何做到这一点。实现这一目标的最佳方法是什么?这不能像在 jQuery 中那样使用 foreach 语句完成吗?

采纳答案by AZ.

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

我在我的项目中使用 Json.net 并且效果很好。在你的情况下,你可以这样做来解析你的 json:

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

编辑:我更改了代码,因此它支持读取您的 json 文件(数组)

Code to parse:

要解析的代码:

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 LinqPadto test your code, easier than creating a solution or project in Visual Studio I think.

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

回答by Guillaume86

you can try with System.Web.Script.Serialization.JavaScriptSerializer:

你可以尝试System.Web.Script.Serialization.JavaScriptSerializer

var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(jsonStr);

回答by Erwin

Instead of an arraylist or dictionary you can also use a dynamic. Most of the time I use EasyHttpfor this, but sure there will by other projects that do the same. An example below:

除了数组列表或字典,您还可以使用动态。大多数时候我使用EasyHttp 来做这件事,但肯定会有其他项目做同样的事情。下面是一个例子:

var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
var response = http.Get("url");
var body = response.DynamicBody;
Console.WriteLine("Name {0}", body.AppName.Description);
Console.WriteLine("Name {0}", body.AppName.Value);

On NuGet: EasyHttp

在 NuGet 上:EasyHttp

回答by Evren Kuzucuoglu

What you are trying to deserialize to a Dictionary is actually a Javascript object serialized to JSON. In Javascript, you can use this object as an associative array, but really it's an object, as far as the JSON standard is concerned.

您尝试反序列化为 Dictionary 的实际上是序列化为 JSON 的 Javascript 对象。在 Javascript 中,您可以将此对象用作关联数组,但就 JSON 标准而言,它实际上是一个对象。

So you would have no problem deserializing what you have with a standard JSON serializer (like the .net ones, DataContractJsonSerializer and JavascriptSerializer) to an object (with members called AppName, AnotherAppName, etc), but to actually interpret this as a dictionary you'll need a serializer that goes further than the Json spec, which doesn't have anything about Dictionaries as far as I know.

因此,您可以将使用标准 JSON 序列化程序(如 .net 序列化程序、DataContractJsonSerializer 和 JavascriptSerializer)的内容反序列化为对象(成员名为 AppName、AnotherAppName 等),但实际上将其解释为字典将需要一个比 Json 规范更进一步的序列化程序,据我所知,它没有任何关于字典的内容。

One such example is the one everybody uses: JSON .net

一个这样的例子是每个人都使用的例子:JSON .net

There is an other solution if you don't want to use an external lib, which is to convert your Javascript object to a list before serializing it to JSON.

如果您不想使用外部库,还有另一种解决方案,即在将 Javascript 对象序列化为 JSON 之前将其转换为列表。

var myList = [];
$.each(myObj, function(key, value) { myList.push({Key:key, Value:value}) });

now if you serialize myList to a JSON object, you should be capable of deserializing to a List<KeyValuePair<string, ValueDescription>>with any of the aforementioned serializers. That list would then be quite obvious to convert to a dictionary.

现在,如果您将 myList 序列化为 JSON 对象,您应该能够List<KeyValuePair<string, ValueDescription>>使用上述任何序列化程序反序列化为 a。然后,该列表很容易转换为字典。

Note: ValueDescription being this class:

注意:ValueDescription 是这个类:

public class ValueDescription
{
    public string Description { get; set; }
    public string Value { get; set; }
}

回答by Kajan Thadsanamoorthy

json:
[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]

c# code: to take only a single value, for example the word "bike".

c# 代码:只取一个值,例如单词“bike”。

//res=[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]

         dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
         string Text = stuff1[0].hws[2];
         Console.WriteLine(Text);

output:

输出:

bike