Deserialize Json to C# Classes

Deserialize JSON to C# Classes

Your problem is twofold:

  1. You don't have a class defined at the root level. The class structure needs to match the entire JSON, you can't just deserialize from the middle.
  2. Whenever you have an object whose keys can change, you need to use a Dictionary<string, T>. A regular class won't work for that; neither will a List<T>.

Make your classes like this:

class RootObject
{
[JsonProperty("results")]
public Results Results { get; set; }
}

class Results
{
[JsonProperty("jobcodes")]
public Dictionary<string, JobCode> JobCodes { get; set; }
}

class JobCode
{
[JsonProperty("_status_code")]
public string StatusCode { get; set; }
[JsonProperty("_status_message")]
public string StatusMessage { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}

Then, deserialize like this:

RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);

Working demo here

Deserialize JSON to class in C#

Try this

public class Account
{
public string Code { get; set; }
public string Status { get; set; }
}


public class AccountWrapper
{
[JsonProperty(PropertyName = "data")]
public string Data { get; set; }

public Account Account
{
get { return JsonConvert.DeserializeObject<Account>(Data); }
}
}

// DeserializeObject
string data = "{'data':'{\"Code\":\"MXXXXX\",\"Status\":\"failed\"}'}";

var account = JsonConvert.DeserializeObject<AccountWrapper>(data).Account;

Deserializing JSON to C# Class

Your #1 attempt was nearly there.

You can do:

var arrays = JsonConvert.DeserializeObject<List<List<object>>>(json);

but then you will have to do the mapping yourself:

var candlesticks =
from values in arrays
select new CandleSticks
{
openTime = Convert.ToInt64(values[0]),
open = Convert.ToString(values[1]),
high = Convert.ToString(values[2]),
...
};

I know that most of the values are already in the right format, so at least for the strings you can probably get by with a case, like high = (string)values[2], but for the longs and ints you really want to use Convert, since small integer values might become ints and higher values might become longs, and then you can't simply cast.

Deserializing JSON with Newtonsoft, using a specific class

Copy your JSON. Open Visual studio. Create new C# class file. Now Select below menu option:

Edit > Paste Special > Paste JSON as classes

This will create a class as below

public class Rootobject
{
public Datum[] data { get; set; }
}

public class Datum
{
public string type { get; set; }
public string id { get; set; }
}

Now change RootObject to jsonTask and deserialise as below

jsonTask test = JsonConvert.DeserializeObject<jsonTask>(strJSON);

C# Deserializing JSON to class dependent on a type property

@OguzOzgul commenting is correct. I've done this countless of times for objects that are composed with interfaces that need to be serialized and deserialized.

See TypeNameHandling for Newtonsoft:
https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm

Your json file will look ever so slightly different:

{
"$type": "SomeNamespace.Bar",
"BarOnly": "This is a string readable when deserialized to the Bar class only, as declared in my type key"
}

If you use

new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
}

During serialization, it will add the full type name of all objects to make sure newtonsoft knows what their type is during deserialization (given you use the same settings then). That way you do not have to write your own custom code for type detection.

C# - Deserialize JSON string into Class

This is your json, fixed with the "\", \r\n and stuf. For future references, please post the correct json.

{
"1":
{
"characterId": 1,
"connectionId": 1,
"accountId": 1,
"name": "Riorage",
"level": 2,
"characterRace": 1,
"characterClass": 1,
"characterPosition": {
"x": "15.42661",
"y": "7.477493",
"z": "-32.30045",
"map": 1

},
"characterRotation": {
"x": "1",
"y": "203",
"z": "1"

},
"charactrerInstance": {
"instanceId": 0,
"groupId": 0

},
"characterState": 1,
"characterMovementState": 0,
"characterActionState": 1,
"characterEmotionState": 1,
"lastOnline": "5.4.2018 г. 14:59:16",
"onlineTime": "1"
}
}

What I think you should do is:

  1. Start by creating a class with the same structure as your json

(I'll post this example and you can set up the other classes and fields)

public class CharacterData
{
[JsonProperty("characterId")] //if you want to reference the field coming in the json, this will allow you to have different name on the property below.
public int characterId;
public int connectionId;
public int accountId;
public string name;
public int level;
public int characterRace;
public int characterClass;
public CharacterPosition characterPosition;
public CharacterRotation characterRotation;
public CharacterInstance charactrerInstance;
public CharacterState characterState;
public CharacterMovementState characterMovementState;
public CharacterActionState characterActionState;
public CharacterEmotionState characterEmotionState;
public string lastOnline;
public string onlineTime;
}

Depending on how you're getting your json, you can retrieve it from some connection or from some string, but be advised that the json must be properly formatted

var deserialized = JsonConvert.DeserializeObject<CharacterData>(YourJsonStringOrResponseHere);

var deserialized = JsonConvert.DeserializeObject<CharacterData>(await response.Content.ReadAsStringAsync());


Related Topics



Leave a reply



Submit