简体   繁体   English

c# - 如何在没有任何模型或映射器的情况下将json转换为对象

[英]How to convert json to object without any model or mapper in c#

How to convert json to object in c#?如何将json转换为c#中的对象? Below is sample of json and some time it can be complex json.下面是 json 的示例,有时它可能是复杂的 json。 I don't want to use any model.我不想使用任何模型。 and not using any mapper.并且不使用任何映射器。 Please suggest something-请提出一些建议-

{'firstName':'Ram','country':'India','email':'test@test.com'}

Json will be different every time like- Json 每次都会有所不同,例如-

{'firstName':'Ram','lastName':'tho','country':'India','email':'test@test.com'}

{'firstName':'Ram','country':'India','state':'MP','city':'Bhp'}

Sample code will be appreciated :) Thanks示例代码将不胜感激:) 谢谢

You can resort to using "json path" or property path notation if you construct a JObject from Newtonsoft based on that data.如果您根据该数据从Newtonsoft构建JObject ,则可以求助于使用“json 路径”或属性路径表示法。

Just don't complain about performance if you do.如果你这样做了,就不要抱怨性能。

I work with JSON and Web-based APIs regularly and will never use anything else than Newtonsoft in C# to handle JSON conversions, it's literally the best possible way to do anything with JSON in C# and without any headaches, it's the most popular C# NuGet package in the world with almost 1 billion downloads, works in ALL .NET versions basically.我经常使用 JSON 和基于 Web 的 API,除了 C# 中的 Newtonsoft 之外,我绝不会使用任何其他东西来处理 JSON 转换,这实际上是在 C# 中使用 JSON 做任何事情的最佳方式,而且没有任何麻烦,它是最受欢迎的 C# NuGet 包在世界上有近 10 亿次下载,基本上适用于所有 .NET 版本。

Here's one of the simplest examples这是最简单的例子之一

string json_string = @"{
                  Firstname: ""Jane"",
                  Lastname: ""Doe"",
                  Age: 36,
                  IsEmployed: true,
                  IsMarried: true,
                  Children: 4
              }";
              
var person = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json_string);

Console.WriteLine(person.Forename);
Console.WriteLine(person.Lastname);
Console.WriteLine(person.Age);
Console.WriteLine(person.IsEmployed);
Console.WriteLine(person.IsMarried);
Console.WriteLine(person.Children);

It generates objects on the fly, no matter the structure!无论结构如何,它都会即时生成对象! Other solutions don't work in all .NET versions.其他解决方案不适用于所有 .NET 版本。

I wrote a simple, easy-to-follow article here https://turmanauli.medium.com/a-complete-guide-for-serializing-json-to-dynamic-objects-on-the-fly-in-c-7ab4799f648d about how to install and use Newtonsoft via NuGet Package Manager in your Visual Studio project.我在这里写了一篇简单易懂的文章https://turmanauli.medium.com/a-complete-guide-for-serializing-json-to-dynamic-objects-on-the-fly-in-c- 7ab4799f648d关于如何在 Visual Studio 项目中通过 NuGet 包管理器安装和使用 Newtonsoft。

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

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