Deserialize JSON into Object C#

Deserialize JSON into Object C#

You can use Visual Studio 2013, 2015 to create your model classes from a json, I did it and I parsed the JSON fine.
To use this feature, you must have JSON/XML in your clipboard, put your cursor inside a .cs file and then use the option Edit > Paste Special > Paste JSON AS Classes

Paste Special JSON as classes

Look the code that was generated:

public class Rootobject
{
public Class1[] Property1 { get; set; }
}

public class Class1
{
public int Rk { get; set; }
public int Gcar { get; set; }
public int Gtm { get; set; }
public string Date { get; set; }
public string Tm { get; set; }
public string Where { get; set; }
public string Opp { get; set; }
public string Rslt { get; set; }
public string Inngs { get; set; }
public int PA { get; set; }
public int AB { get; set; }
public int R { get; set; }
public int H { get; set; }
public int Doubles { get; set; }
public int Triples { get; set; }
public int HR { get; set; }
public int RBI { get; set; }
public int BB { get; set; }
public int IBB { get; set; }
public int SO { get; set; }
public int HBP { get; set; }
public int SH { get; set; }
public int SF { get; set; }
public int ROE { get; set; }
public int GDP { get; set; }
public int SB { get; set; }
public int CS { get; set; }
public float BA { get; set; }
public float OBP { get; set; }
public float SLG { get; set; }
public float OPS { get; set; }
public int BOP { get; set; }
public float aLI { get; set; }
public float WPA { get; set; }
public float RE24 { get; set; }
public int DFSDK { get; set; }
public float DFSFD { get; set; }
public string Pos { get; set; }
}

In runtime to deserialize JSON into this object created from Visual Studio, you can use Newtonsoft.Json, you can install this using nuget with the following command:

Install-Package Newtonsoft.Json

Now you can deserialized it, using the gerenric method DeserializedObject from the static class JsconCovert, like that:

Rootobject object = JsonConvert.DeserializeObject<Rootobject>(jsonString); 

How to deserialize Json to an object?

var s = "{\r\n  \"Status\": \"PLANNED\"\r\n}";
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<StatusModel>(s);

The model you have defined is incorrect.
Your model should be like this:

public class StatusModel
{
public string Status { get; set; }
}

Now value will be extracted to this model and you can access the value like:

var value = obj.Status; //"PLANNED"

Deserialize a JSON into a list of C# objects

The best move would be deserializing it as Dictionary<string, object> and Iterate through the values and casting them to your desired "Item" class.

Deserialize json to Listobject in C#

There is an error in your json - it's missing a closing ] for the array (I'll assume it's a typo).

The real problem is that you need a wrapper class to represent the data node of the json which should contain a list (or array) of ExPositions. The makerPositions and takerPositions should also become lists (or arrays) too. Add the following class and update the position properties of ExPositions:

public class Data
{
public List<ExPositions> data { get; set; }
}

// change positions to use a List too
public class ExPositions
{
...
public List<Positions> makerPositions { get; set; }
public List<Positions> takerPositions { get; set; }
}

Then you can deserialize using:

var result = JsonSerializer.Deserialize<Data>(json);

It's not clear where the ""total"": 2 property should be in your models (it's not clear in the json because of the issue I mentioned), you could add it to the Data class above (if it belongs there).

Online demo

How to deserialize json inside a json to a string property

One workaround is to add a field to Unit called CostCentersString in which the CostCenters list is re-serialized:

In Unit class definition:

...

public List<dynamic> CostCenters { get; set; }

public String CostCentersString { get; set; }

Then use:

List<Unit> units = JsonConvert.DeserializeObject<List<Unit>>(jsonString);

foreach (Unit u in units)
{
u.CostCentersString = JsonConvert.SerializeObject(u.CostCenters);
}

Deserialize JSON into an object, and then run a foreach loop to add into a listview

try to use List instead of GameListObject, and you dont need foreach loop in this case

//Deserialise the return output into game id, game name and release date
List<GameListObject> gamelistobjects = JsonSerializer.Deserialize<List<GameListObject>>(httpResponseBody);

ObservableCollection<GameListObject> dataList =
new ObservableCollection<GameListObject>(gamelistobjects);

or even one line would be ok

 ObservableCollection<GameListObject> dataList = JsonConvert.DeserializeObject<ObservableCollection<GameListObject>>(json);

test


foreach (var item in dataList)
{
Debug.WriteLine($"id: {item.GameID}");
Debug.WriteLine($"name: {item.GameName}");

if(item.ReleaseDates!=null)
foreach (var date in item.ReleaseDates)
{
Debug.WriteLine($"releaseDate: {date.Human}");
}
}

output

d: 277
name: Battlefield 2
releaseDate: Jun 21, 2005
releaseDate: Jun 22, 2005
releaseDate: Jun 24, 2005
id: 89571
name: Battlefield V: Deluxe Edition
releaseDate: Nov 16, 2018
releaseDate: Nov 16, 2018
releaseDate: Nov 16, 2018

and try this clasess

public partial class GameListObject
{
[JsonProperty("id")]
public long GameID { get; set; }

[JsonProperty("name")]
public string GameName { get; set; }

[JsonProperty("release_dates")]
public ObservableCollection<ReleaseDate> ReleaseDates { get; set; }
}

public partial class ReleaseDate
{
[JsonProperty("id")]
public long Id { get; set; }

[JsonProperty("human")]
public string Human { get; set; }
}

public partial class ReleaseDate
{
[JsonProperty("id")]
public long Id { get; set; }

[JsonProperty("human")]
public string Human { get; set; }
}

How Can I deserialize a json into a structure?

Yet another solution could be to make use of the JsonSchema

First let's redefine your data model:

public abstract class Settings
{
[JsonProperty("id")]
public string Id { get; set; }

[JsonProperty("type")]
public string Type { get; set; }
}

public class SettingsV1 : Settings
{
[JsonProperty("content")]
public string Content { get; set; }
}

public class SettingsV2 : Settings
{
[JsonProperty("content")]
public Content Content { get; set; }
}

public class Content
{
[JsonProperty("id")]
public string Id { get; set; }

[JsonProperty("duration")]
public long Duration { get; set; }
}
  • Instead of having a middle man (ContentStructure) rather than you can have two separate Settings versions
  • The common fields are defined inside the abstract base class

Now, you can use these two versioned classes to define json schemas:

private static JSchema schemaV1;
private static JSchema schemaV2;

//...
var generator = new JSchemaGenerator();
schemaV1 = generator.Generate(typeof(SettingsV1));
schemaV2 = generator.Generate(typeof(SettingsV2));

Finally all you need to do is to do a preliminary check before calling the DeserializeObject with the proper type:

Settings settings = null;
var semiParsed = JObject.Parse(json);
if (semiParsed.IsValid(schemaV1))
{
settings = JsonConvert.DeserializeObject<SettingsV1>(json);
}
else if (semiParsed.IsValid(schemaV2))
{
settings = JsonConvert.DeserializeObject<SettingsV2>(json);
}
else
{
throw new NotSupportedException("The provided json format is not supported");
}


Related Topics



Leave a reply



Submit