How to convert json to object in c#? Below is sample of json and some time it can be complex 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-
{'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.
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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.