简体   繁体   English

如何在net-core 2.0中手动解析JSON字符串

[英]How to manually parse a JSON string in net-core 2.0

I have a json string with the following structure 我有一个具有以下结构的json字符串

{
    "resource": "user",
    "method": "create",
    "fields": {
        "name": "John",
        "surname: "Smith",
        "email": "john@gmail.com"
    }
}

The keys inside fields are variable, that means I don't know them in advance 字段内的键是可变的,这意味着我事先不知道它们

So, instead of deserializing a json string to an object, I need to traverse the json, in order to get the properties inside fields in a Dictionary or something like that. 因此,我不需要将json字符串反序列化为对象,而是需要遍历json,以便获取Dictionary中字段内的属性或类似的东西。

I heard about the Json.NET library and it's ability to parse dynamic jsons, but I'm not sure it it's already included in net-core or not. 我听说过Json.NET库,它能够解析动态jsons,但我不确定它是否已经包含在net-core中了。

What would be the standard / easiest way to accomplish that in net-core 2.0. 在net-core 2.0中实现这一目标的标准/最简单方法是什么? Code example would be appreciated. 代码示例将不胜感激。

Yes. 是。 You can add Newtonsoft.json package to your .net core project. 您可以将Newtonsoft.json包添加到.net核心项目中。 And to query the dynamic json object, you can use the JObject object provided by the library to parse your json into a dynamic object. 要查询动态json对象,可以使用库提供的JObject对象将json解析为动态对象。 Here is the link for the document. 这是该文档的链接

Given your json sample it may look like this 鉴于你的json样本,它可能看起来像这样

 var resource = JObject.Parse(json);
 foreach (var property in resource.fields.Properties())
 {
   Console.WriteLine("{0} - {1}", property.Name, property.Value);
 }

Json.NET is the go-to library when you are serializing .NET objects. 当您序列化.NET对象时, Json.NET首选库。 However, when structure of objects is not static, APIs from System.Json namespace will be simpler to use. 但是,当对象的结构不是静态时,System.Json命名空间中的API将更易于使用。 System.Json can be used in .NET Core 2.0 by installing a package from NuGet like this: 通过从NuGet安装包,可以在.NET Core 2.0中使用System.Json,如下所示:

dotnet add package System.Json --version 4.4.0

Here is a nice tutorial on how to use APIs from System.Json namespace: Working with JSON in .NET – a Silverlight example 这是一个很好的教程,介绍如何使用System.Json命名空间中的API: 在.NET中使用JSON - 一个Silverlight示例

using System.Web.Script.Serialization;
using System.Dynamic;

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic jsonObject = serializer.Deserialize(jsonString, typeof(Example));

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

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