How can I map JSON to a .NET class - c#

I want to map this JSON into a .NET class. How can I map this JSON data into a class? Please suggest how. Here is the json:
{"results": [
"43853",
"43855",
"43856",
"43857",
{
"questionType": 3,
"choiceAnswers": [123]
}
]}

The easiest solution is to use Visual Studio Edit > Paste Special > Paste Json As Classes.
But as your json is an array of different objects the .NET class will just be
public class JsonDto
{
public List<object> Results { get; set; }
}
A list of objects will be painful to work with so I recommend that you to use a typed model but then you need to specify you need to define the values, here's an example
{"results": [
{
"key1":"43853",
"key2":"43855",
"key3":"43856",
"key4":"43857",
"question": {
"questionType": 3,
"choiceAnswers": [123]
}
}
]};
public class JsonDto
{
public List<ResultDto> Results { get; set; }
}
public class ResultDto
{
public string Key1 { get; set; }
public string Key2 { get; set; }
public string Key3 { get; set; }
public string Key4 { get; set; }
public QuestionDto Question { get; set; }
}
public class QuestionDto
{
public int QuestionType { get; set; }
public List<int> ChoiceAnswers { get; set; }
}

You can use online converter to convert json data to c# models http://json2csharp.com For your json it would be something like this.
public class RootObject
{
public List<object> results { get; set; }
}

Related

How to parse JSON dynamic KeyValuePair to C# model in Blazor WASM [duplicate]

I have json that looks like this, the key "123" could be any number.
{
"key1": "",
"key2": {
"items": {
"123": {
"pageid": 123,
"name": "data"
}
}
}
}
I want to deserialize or query the json with System.Text.Json so i can get the value of the key "name". How can I do that with System.Text.Json? I'm using .NET Core 3.1.
Since one of the json keys can vary ("123"), this can be represented by a Dictionary<>. The following classes model your json.
public class ItemProps
{
public int pageid { get; set; }
public string name { get; set; }
}
public class Item
{
public Dictionary<string, ItemProps> items { get; set; }
}
public class Root
{
public string key1 { get; set; }
public Item key2 { get; set; }
}
Then to deserialize using System.Text.Json you would use:
var data = JsonSerializer.Deserialize<Root>(json);
To access name:
var name = data.key2.items["123"].name
Try it online
Note, I named the classes quickly... please consider giving the classes better names, more descriptive names.
Something like:
public class Rootobject
{
public string key1 { get; set; }
public InnerObject key2 { get; set; }
}
public class InnerObject
{
public Dictionary<string, ObjectTheThird> items { get; set; }
= new Dictionary<string, ObjectTheThird>();
}
public class ObjectTheThird
{
public int pageid { get; set; }
public string name { get; set; }
}
and use the APIs on Dictionary<,> to look at the items. Or you just want the first:
var name = obj.key2.items.First().Value.name;

Custom JSON Serialize with custom mapping C#

I want to serialize/deserialize the following JSON:
{
"result": {
"ID": 1,
"TITLE": "Example",
"ARRAY": [
{
"Item1": "Result1",
"Item2": "Result2"
}
]
}
}
I tried with the following class format, but no sucess yet... Can someone help me deserialize it?
public class myClass
{
public string ID { get; set; }
[JsonProperty("TITLE")]
public string Name { get; set; }
}
obs.: Using the namespace Newtonsoft.JSON
In your example class definition above, you have called the class myClass but you would have had to call it result because ID and TITLE are members of the result JSON in the given example. myClass would not resolve to anything.
I don't know why you'd want to have a property called Name that is mapped to TITLE, but ok, if you want to do that you can modify the solution after you get it working.
Still, we're not done yet. You also have a JSON member called ARRAY and you need to define a separate class for that.
And still there is an additional problem: the result JSON is nested inside an implicit base object, so we need to define that as well. Let's call it BaseResult.
public class ARRAY
{
public string Item1 { get; set; }
public string Item2 { get; set; }
}
public class Result
{
public int ID { get; set; }
public string TITLE { get; set; }
public List<ARRAY> ARRAY { get; set; }
}
public class BaseResult
{
public Result result { get; set; }
}
If you are using Visual Studio, you can copy your JSON and paste it in any *.cs file with Edit > Paste Special > Paste JSON as Classes. It will generate POCO objects representing your JSON, which in your case will be this:
public class Rootobject
{
public Result result { get; set; }
}
public class Result
{
public int ID { get; set; }
public string TITLE { get; set; }
public ARRAY[] ARRAY { get; set; }
}
public class ARRAY
{
public string Item1 { get; set; }
public string Item2 { get; set; }
}
Then, asuming that you have your JSON in a string variable named data, you can deserialize it as follows:
var result= JsonConvert.DeserializeObject<Rootobject>(data);

How to deserialize a Json string that has an array of objects but is not using square brackets

I'm trying to deserialize a Json string that has an array with no containing brackets.
{ "id": "983f90j30909j3f",
"moreInfo": {
"info193802": { ... },
"info920938": { ... },
"info849028": { ... }
}
}
This "moreInfo" is an array of items with dynamic keys and does not have square brackets telling that it's an array.
I've tried to deserialize it with Newtonsoft.Json normally ( JsonConvert.DeserializeObject<rootObject>() ) but since this json array isn't really an array it throws an error. Here is my class:
public class RootObject
{
public string Id { get; set; }
public MoreInfo MoreInfo { get; set; }
}
public class MoreInfo
{
public List<Info> InfoList{ get; set; }
}
public class Info
{
properties...
}
How do I go about deserializing this?
Update the root object to use IDictionary<string, Info>
public class RootObject {
public string Id { get; set; }
public IDictionary<string, Info> MoreInfo { get; set; }
}
the dynamic keys will be the key in the dictionary.
Once parsed you access the info via the dictionary's keys
Info info = rootObject.MoreInfo["info193802"];
Newtonsoft can correctly parse the data. The data represents objects, they happen to be nested fairly deep. You can accomplish it a couple of ways, for instance:
dynamic json = JsonConvert.DeserializeObject(response);
var info = json["moreinfo:info913802:example"].Value;
Your other option would be to use Visual Studio, let it create an object you can deserialize to.
Edit
Paste Special
As JSON
Output would be:
public class Rootobject
{
public string id { get; set; }
public Moreinfo moreInfo { get; set; }
}
public class Moreinfo
{
public Info193802 info193802 { get; set; }
public Info920938 info920938 { get; set; }
public Info849028 info849028 { get; set; }
}
public class Info193802
{
public string Example { get; set; }
}
public class Info920938
{
public string Example { get; set; }
}
public class Info849028
{
public string Example { get; set; }
}
The source JSON I used was yours, with one exception:
{ "id": "983f90j30909j3f",
"moreInfo": {
"info193802": { "Example" : "Blah" },
"info920938": { "Example" : "Blah" },
"info849028": {"Example" : "Blah" }
}
}

How to create c# class for below format JSON

Could someone help me in structuring the class for below format JSON.
I have already tried http://json2csharp.com/ tool. It did not work as my list of people are dynamic, i.e. values 123, 124 etc are not pre-defined.
{
"people":
{
"123":"jack henry",
"124":"john henry",
"125":"jill henry",
"215":"jim henry",
...
}
}
public class Root
{
public Dictionary<string, string> people = new Dictionary<string,string>();
}
Using Json.NET:
Root root = new Root();
root.people.Add("123", "jack henry");
//... Add more people
string json = JsonConvert.SerializeObject(root);
Visual Studio > Edit > Paste Special > Paste JSON as classes
public class Rootobject
{
public People people { get; set; }
}
public class People
{
public string _123 { get; set; }
public string _124 { get; set; }
public string _125 { get; set; }
public string _215 { get; set; }
}
You already got an answer for your question. But, looking at the sample JSON looks like you are actually storing a list of persons. If that is the case, you might create classes like this
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class People
{
public List<Person> Persons { get; set; }
//other properties
}
And have your JSON standardized as
{
"Persons": [
{
"Id": 123,
"Name": "Jack"
},
{
"Id": 124,
"Name": "John"
}
]
}
Which will be much more meaningful and readable (by code and human).
Source: http://json2csharp.com/
public class People
{
public string __invalid_name__123 { get; set; }
public string __invalid_name__124 { get; set; }
public string __invalid_name__125 { get; set; }
public string __invalid_name__215 { get; set; }
}
public class RootObject
{
public People people { get; set; }
}

Deserializing a JSON file using C#

I'm creating a Steam APP ( For the Steam Platform ), and i need to deserialize a JSON file.
{
"response": {
"success": 1,
"current_time": 1401302092,
"raw_usd_value": 0.245,
"usd_currency": "metal",
"usd_currency_index": 5002,
"items": {
"A Brush with Death": {
"defindex": [
30186
],
"prices": {
"6": {
"Tradable": {
"Craftable": [
{
"currency": "metal",
"value": 4,
"last_update": 1398990171,
"difference": 0.17
}
]
}
}
}
},
...
I just need to get Defindex and value. Already deserialized some simple JSON files, but i think this one is more complex.
For those who wants to know, I am using the API from BackpackTF...
Use NewtonSoft.Json And then you can use it as follows to get the data out.
dynamic json = JsonConvert.DeserializeObject(<yourstring>);
string currency = json.response.usd_currency; // "metal"
In general, what you want to do is making sure you have valid JSON (use JSON LINT for that), then get a C# class definition with Json2CSharp, then you will do something like this:
MyClass myobject=JsonConvert.DeserializeObject<MyClass>(json);
(We're assuming MyClass is based on what you got from Json2CSharp)
Then you access the values you want via the traditional C# dot notation.
Use a nuget package caller Newtonsoft.Json.5.0.8. it is on the nuget repository.
This line of code will take your json as a string, and turn it into its root object.
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonString);
The Json you provided is slightly flawed, but im guessing that the structure of c# objects you would be looking for would be close to this:
public class Craftable
{
public string currency { get; set; }
public int value { get; set; }
public int last_update { get; set; }
public double difference { get; set; }
}
public class Tradable
{
public List<Craftable> Craftable { get; set; }
}
public class Prices
{
public Tradable Tradable{ get; set; }
}
public class Items
{
public List<int> defindex { get; set; }
public Prices prices { get; set; }
}
public class Response
{
public int success { get; set; }
public int current_time { get; set; }
public double raw_usd_value { get; set; }
public string usd_currency { get; set; }
public int usd_currency_index { get; set; }
public Items items { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}

Categories

Resources