Deserialize Json With C#

Deserialize JSON with C#

You need to create a structure like this:

public class Friends
{

public List<FacebookFriend> data {get; set;}
}

public class FacebookFriend
{

public string id {get; set;}
public string name {get; set;}
}

Then you should be able to do:

Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);

The names of my classes are just an example. You should use proper names.

Adding a sample test:

string json =
@"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";

Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(json);

foreach(var item in facebookFriends.data)
{
Console.WriteLine("id: {0}, name: {1}", item.id, item.name);
}

Produces:

id: 518523721, name: ftyft
id: 527032438, name: ftyftyf
id: 527572047, name: ftgft
id: 531141884, name: ftftft

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); 

Deserialize JSON into C# dynamic object?

If you are happy to have a dependency upon the System.Web.Helpers assembly, then you can use the Json class:

dynamic data = Json.Decode(json);

It is included with the MVC framework as an additional download to the .NET 4 framework. Be sure to give Vlad an upvote if that's helpful! However if you cannot assume the client environment includes this DLL, then read on.


An alternative deserialisation approach is suggested here. I modified the code slightly to fix a bug and suit my coding style. All you need is this code and a reference to System.Web.Extensions from your project:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

public sealed class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");

return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
}

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}

public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); }
}

#region Nested type: DynamicJsonObject

private sealed class DynamicJsonObject : DynamicObject
{
private readonly IDictionary<string, object> _dictionary;

public DynamicJsonObject(IDictionary<string, object> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
_dictionary = dictionary;
}

public override string ToString()
{
var sb = new StringBuilder("{");
ToString(sb);
return sb.ToString();
}

private void ToString(StringBuilder sb)
{
var firstInDictionary = true;
foreach (var pair in _dictionary)
{
if (!firstInDictionary)
sb.Append(",");
firstInDictionary = false;
var value = pair.Value;
var name = pair.Key;
if (value is string)
{
sb.AppendFormat("{0}:\"{1}\"", name, value);
}
else if (value is IDictionary<string, object>)
{
new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb);
}
else if (value is ArrayList)
{
sb.Append(name + ":[");
var firstInArray = true;
foreach (var arrayValue in (ArrayList)value)
{
if (!firstInArray)
sb.Append(",");
firstInArray = false;
if (arrayValue is IDictionary<string, object>)
new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);
else if (arrayValue is string)
sb.AppendFormat("\"{0}\"", arrayValue);
else
sb.AppendFormat("{0}", arrayValue);

}
sb.Append("]");
}
else
{
sb.AppendFormat("{0}:{1}", name, value);
}
}
sb.Append("}");
}

public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!_dictionary.TryGetValue(binder.Name, out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}

result = WrapResultObject(result);
return true;
}

public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (indexes.Length == 1 && indexes[0] != null)
{
if (!_dictionary.TryGetValue(indexes[0].ToString(), out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}

result = WrapResultObject(result);
return true;
}

return base.TryGetIndex(binder, indexes, out result);
}

private static object WrapResultObject(object result)
{
var dictionary = result as IDictionary<string, object>;
if (dictionary != null)
return new DynamicJsonObject(dictionary);

var arrayList = result as ArrayList;
if (arrayList != null && arrayList.Count > 0)
{
return arrayList[0] is IDictionary<string, object>
? new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x)))
: new List<object>(arrayList.Cast<object>());
}

return result;
}
}

#endregion
}

You can use it like this:

string json = ...;

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

dynamic obj = serializer.Deserialize(json, typeof(object));

So, given a JSON string:

{
"Items":[
{ "Name":"Apple", "Price":12.3 },
{ "Name":"Grape", "Price":3.21 }
],
"Date":"21/11/2010"
}

The following code will work at runtime:

dynamic data = serializer.Deserialize(json, typeof(object));

data.Date; // "21/11/2010"
data.Items.Count; // 2
data.Items[0].Name; // "Apple"
data.Items[0].Price; // 12.3 (as a decimal)
data.Items[1].Name; // "Grape"
data.Items[1].Price; // 3.21 (as a decimal)

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"

C# JSON Deserialization: How to get values out of a JSON array of objects

{
"project": [
{
"id": 1,
"keyName": "John123",
"age": "19",
"token": "123456789"
},
{
"id": 2,
"keyName": "Mary123",
"age": "13",
"token": "23435"
},
{
"id": 3,
"keyName": "Harry123",
"age": "23",
"token": "2343542"
}
]
}

You can use Newtonsoft.Json framework for json manipulation, which you can install from NuGet Package Manager. Then do a Project model with the data that you need. You can abstract it even further with JSONData class, so if your json data grows you can just add new properties to it. After that just deserialize it.

public class Project
{
public string KeyName { get; set; }
public string Token { get; set; }
}

public class JSONData
{
public List<Project> Projects { get; set; }
}

public class Deserializer
{
//---------------- FIELDS -----------------
private readonly string path = @"../../yourJsonFile.json";
private readonly JSONData jsonData;

//------------- CONSTRUCTORS --------------
public Deserializer() {
this.jsonData = JsonConvert.DeserializeObject<JSONData>(File.ReadAllText(this.path));
}
}

That way you won't duplicate deserialization code like this

JsonConvert.DeserializeObject<List<Project>>(path);
JsonConvert.DeserializeObject<List<Category>>(path);
JsonConvert.DeserializeObject<List<Product>>(path);

How to deserialize nested JSON in C#

All code was tested using VS2019 and working properly.

The simpliest way will be

var root =Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var path = root + @"\SubtitleTranslator\LanguagesList.json";
var json = File.ReadAllText(path);
var jsonDeserialized = JsonConvert.DeserializeObject<Root>(json);
List<Language> languages = null;
if( jsonDeserialized.StatusCode== 200) languages=jsonDeserialized.Result.languages;

or if you don't need any data except languages, try this code

var languages= JObject.Parse(json)["Result"]["languages"].ToObject<Language[]>();

in this case you will need only Language class

OUTPUT (in both cases)

[{"language":"af","language_name":"Afrikaans","native_language_name":"Afrikaans","country_code":"ZA","words_separated":true,"direction":"left_to_right","supported_as_source":false,"supported_as_target":false,"identifiable":true},
{"language":"ar","language_name":"Arabic","native_language_name":"العربية","country_code":"AR","words_separated":true,"direction":"right_to_left","supported_as_source":true,"supported_as_target":true,"identifiable":true},
{"language":"az","language_name":"Azerbaijani","native_language_name":"آذربایجان دیلی","country_code":"AZ","words_separated":true,"direction":"right_to_left","supported_as_source":false,"supported_as_target":false,"identifiable":true}]

Update

you can test it using Console.WriteLine

foreach (var lg in languages)
{
Console.WriteLine($"Language Name: {lg.native_language_name}, Coutry Code: {lg.country_code}");

}

Language class

public class Language
{
public string language { get; set; }
public string language_name { get; set; }
public string native_language_name { get; set; }
public string country_code { get; set; }
public bool words_separated { get; set; }
public string direction { get; set; }
public bool supported_as_source { get; set; }
public bool supported_as_target { get; set; }
public bool identifiable { get; set; }
}

another classes (if needed)

public class Root
{
public int StatusCode { get; set; }
public Headers Headers { get; set; }
public Result Result { get; set; }
}
public class Headers
{
[JsonProperty("X-XSS-Protection")]
public string XXSSProtection { get; set; }

[JsonProperty("X-Content-Type-Options")]
public string XContentTypeOptions { get; set; }

[JsonProperty("Content-Security-Policy")]
public string ContentSecurityPolicy { get; set; }

[JsonProperty("Cache-Control")]
public string CacheControl { get; set; }
public string Pragma { get; set; }

[JsonProperty("Strict-Transport-Security")]
public string StrictTransportSecurity { get; set; }

[JsonProperty("x-dp-watson-tran-id")]
public string XDpWatsonTranId { get; set; }

[JsonProperty("X-Request-ID")]
public string XRequestID { get; set; }

[JsonProperty("x-global-transaction-id")]
public string XGlobalTransactionId { get; set; }
public string Server { get; set; }

[JsonProperty("X-EdgeConnect-MidMile-RTT")]
public string XEdgeConnectMidMileRTT { get; set; }

[JsonProperty("X-EdgeConnect-Origin-MEX-Latency")]
public string XEdgeConnectOriginMEXLatency { get; set; }
public string Date { get; set; }
public string Connection { get; set; }
}


public class Result
{
public List<Language> languages { get; set; }
}
````

Deserialize JSON with an array into DataTable?

You got an deserialize error "... Expected StartArray, got StartObject." So you can not to deserialize to DataTable the whole object , you need an array part only. An array part starts from "artists". So after parsing the whole object you have to deserilize "artists" part only.

try this. it was tested in Visual Studio

var jsonObject=JObject.Parse(json);
DataTable dt = jsonObject["artists"].ToObject<DataTable>();


Related Topics



Leave a reply



Submit