Properly deserialize object with RootObject [duplicate] - c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Facebook;
using Newtonsoft.Json;
namespace facebook
{
class Program
{
static void Main(string[] args)
{
var client = new FacebookClient(acc_ess);
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);
//jsonstring {"data":[{"target_id":9503123,"target_type":"user"}]}
List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);
}
public class Datum
{
public Int64 target_id { get; set; }
public string target_type { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
}
}
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type
'System.Collections.Generic.List`1[facebook.Program+RootObject]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly. To fix this error either change the JSON to a JSON array
(e.g. [1,2,3]) or change the deserialized type so that it is a normal
.NET type (e.g. not a primitive type like integer, not a collection
type like an array or List) that can be
I looked at other posts.
My json looks like this:
{"data":[{"target_id":9503123,"target_type":"user"}]}

To make it clear, in addition to #SLaks' answer, that meant you need to change this line :
List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);
to something like this :
RootObject datalist = JsonConvert.DeserializeObject<RootObject>(jsonstring);

As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>).
You want to deserialize into a single RootObject.

Can you try to change your json without data key like below?
[{"target_id":9503123,"target_type":"user"}]

That happened to me too, because I was trying to get an IEnumerable but the response had a single value. Please try to make sure it's a list of data in your response. The lines I used (for api url get) to solve the problem are like these:
HttpResponseMessage response = await client.GetAsync("api/yourUrl");
if (response.IsSuccessStatusCode)
{
IEnumerable<RootObject> rootObjects =
awaitresponse.Content.ReadAsAsync<IEnumerable<RootObject>>();
foreach (var rootObject in rootObjects)
{
Console.WriteLine(
"{0}\t${1}\t{2}",
rootObject.Data1, rootObject.Data2, rootObject.Data3);
}
Console.ReadLine();
}
Hope It helps.

The real problem is that you are using dynamic return type in the FacebookClient Get method. And although you use a method for serializing, the JSON converter cannot deserialize this Object after that.
Use insted of:
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);
something like that:
string result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}).ToString();
Then you can use DeserializeObject method:
var datalist = JsonConvert.DeserializeObject<List<RootObject>>(result);
Hope this helps.

public partial class tree
{
public int id { get; set; }
public string name { get; set; }
public string sciencename { get; set; }
public int familyid { get; set; }
}
private async void PopulateDataGridView()
{
//For Single object response
tree treeobj = new tree();
treeobj = JsonConvert.DeserializeObject<tree>(Response);
//For list of object response
List<tree> treelistobj = new List<tree>();
treelistobj = JsonConvert.DeserializeObject<List<tree>>(Response);
//done
}

Related

Deserializing a JSON file with c#

My problem is
i have this JSON file:
and i have to save it in a list but when i try to print the first element of the list I get a System.ArgumentOutOfRangeException, as if my list is empty. this is my code:
JavaScriptSerializer ser = new JavaScriptSerializer();
Causali o = new Causali();
List<CausaliList> lista = new List<CausaliList>();
WebRequest causali = (HttpWebRequest)WebRequest.Create("http://trackrest.cgestmobile.it/causali");
WebResponse risposta = (HttpWebResponse)CreateCausaliRequest(causali).GetResponse();
Stream data = risposta.GetResponseStream();
StreamReader Leggi = new StreamReader(data);
string output = Leggi.ReadToEnd();
lista = ser.Deserialize<List<CausaliList>>(output);
lst2.Items.Add(lista[0]);
and these are my two class for the saves:
class Causali
{
public int id;
public string causaliname;
public string identificationcode;
public string expired;
}
and
class CausaliList
{
public Causali causali;
}
can you help me solve it?
please try this as your root object:
public class CausaliList
{
public List<Causali> causali { get; set; }
}
then deserilize your object like this:
lista = ser.Deserialize<CausaliList>(output);
finally you can access to list like this:
lst2.Items.Add(lista.causali[0]);
Note: i strongly recommend to use json.NET.
To deserialize the code in c#:
Lets assume you have data in var getContent then you may use this:
dynamic getDesearilize = JsonConvert.DeserializeObject(getContent);

Deserialize list of JSON objects

I got a Windows Phone 8.1 app.
I am trying to parse a list of objects returned by my Web API call.
On my server I have this code:
Default.aspx:
[WebMethod]
public static List<Shared.PremisesResponse> GetPremises(string emailaddress)
{
Premises premises = new Premises();
return premises.GetPremises(emailaddress);
}
In that premise object class
public List<Shared.PremisesResponse> GetPremises(string emailAlias)
{
DAL dal = new DAL();
List<Shared.PremisesResponse> premises = new List<Shared.PremisesResponse>();
try
{
DataSet dtMacs = dal.GetMacs(emailAlias);
for (int index = 0; index < dtMacs.Tables[0].Rows.Count; index++)
{
Shared.PremisesResponse itemMAC1 = new Shared.PremisesResponse();
itemMAC1.PremiseName = dtMacs.Tables[0].Rows[index]["PremiseName"].ToString().Trim();
itemMAC1.Alias = dtMacs.Tables[0].Rows[index]["Alias"].ToString().Trim();
premises.Add(itemMAC1);
}
}
catch (Exception ex)
{
Email2.SendError("Premises.GetPremises:" + ex.ToString(), emailAlias);
Shared.PremisesResponse itemMAC1 = new Shared.PremisesResponse();
itemMAC1.PremiseName = "ERROR";
itemMAC1.Alias = ex.ToString();
premises.Add(itemMAC1);
}
return premises;
}
The class Shared.Premise:
public class PremisesResponse
{
public string PremiseName;
public string Alias;
}
In my WP8.1 client app:
public async static Task<List<D2>> GetPremises( string emailaddress)
{
List<D2> premises = new List<D2>();
try
{
using (var client = new HttpClient())
{
var resp = await client.PostAsJsonAsync("http://my url/NativeApp/Default.aspx/GetPremises",
new { emailaddress = emailaddress });
var str = await resp.Content.ReadAsStringAsync();
var premisesResponse = JsonConvert.DeserializeObject<List<D2>>(str);
foreach (var pr in premisesResponse)
{
D2 d2 = new D2();
d2.Alias = pr.Alias;
d2.PremiseName = pr.PremiseName;
premises.Add(d2);
}
}
}
catch (Exception ex)
{
//evMessage(Enums.MessageType.Error, serverRegister);
}
return premises;
}
And the objects I am using in my client:
public class D2
{
public string __type { get; set; }
public string PremiseName;
public string Alias;
}
public class PremisesResponse
{
public D2 d { get; set; }
}
'var str' returns this value:
{"d":[{"__type":"InformedMotionBiz.Shared+PremisesResponse","PremiseName":"Informatica 2000","Alias":"9A5C3-E1945-3D315-BB43C"},{"__type":"InformedMotionBiz.Shared+PremisesResponse","PremiseName":"My Office","Alias":"40387-69918-FC22F-C444B"}]}
The error occurs on this line:
var premisesResponse = JsonConvert.DeserializeObject<List<PremisesResponse>>(str);
The error message is:
[Informed.D2]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'd', line 1, position 5.
I have no problems returning a single value, just with returning a list of this object.
Any pointers would be helpful.
Thanks
You're trying to deserialize a List<D2> rather than a single D2 object:
public class PremisesResponse
{
public D2[] d { get; set; }
}
And then simply:
PremisesResponse response = JsonConvert.DeserializeObject<PremisesResponse>(str);

JSON parsing of a complex object

Given below is the type of JSON response ,
{
"?xml":{
"#version":"1.0",
"#encoding":"iso-8859-1"
},
"xmlreport":{
"#title":"ABC: TEST Most Saved2",
"#dates":"Week of May 19,2013",
"columns":{
"column":[
{
"#name":"Page",
"#type":"dimension",
"#text":"Page"
},
{
"#name":"Events",
"#type":"metric",
"#hastotals":"true",
"#text":"Events"
}
]
},
"rows":{
"row":[
{
"#rownum":"1",
"cell":[
{
"#columnname":"page",
"#csv":"\"http://www.ABC.com/profile/recipebox\"",
"#text":"http://www.ABC.com/profile/recipebox"
},
{
"#columnname":"events",
"#percentage":"\"0.1%\"",
"#text":"489"
}
]
},
{
"#rownum":"2",
"cell":[
{
"#columnname":"page",
"#csv":"\"http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c\"",
"#text":"http://www.ABC.com/recip...c602e4-007b-43e0-aaab-2f9aed89524c"
},
{
"#columnname":"events",
"#percentage":"\"0.0%\"",
"#text":"380"
}
]
}
]
},
"totals":{
"pagetotals":{
"total":{
"#columnname":"events",
"#value":"1820.000000",
"#text":"1,820 (0.2%)"
}
},
"reporttotals":{
"total":{
"#columnname":"events",
"#value":"7838.000000",
"#text":"7,838 (0.8%)"
}
},
"timeperiodtotals":{
"total":{
"#columnname":"events",
"#value":"955774.000000",
"#text":"955,774 (100.0%)"
}
}
}
}
}
I am unable to parse the object.Could you please help me out how do I read the attributes and elements after parsing. I am using C#
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(XML);
string jsonText = JsonConvert.SerializeXmlNode(doc);
//var result = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(jsonText, "xmlreport");
var results = JsonConvert.DeserializeObject<dynamic>(jsonText);
JToken token = JObject.Parse(jsonText);
var report = token["xmlreport"];
}
My understanding of the question is you've got some Xml and you need to send out json. Couple of points before we get to the code:
1) Don't convert xml to json directly as it causes issues
2) Parse the xml to objects at your end and then work out the format to return; decoupling what comes in and goes out will allow for one of the interfaces to change in the future without impacting the other as you can tweak the mapping
So, onto the code ...
Essentially parse the xml to objects to allow for further processing and then push out as json.
class Program
{
private static string starting =
"<xmlreport title=\"ABC: TEST Most Saved2\" dates=\"Week of May 19,2013\"><columns><column name=\"Page\" type=\"dimension\">Page</column><column name=\"Events\" type=\"metric\" hastotals=\"true\">Events</column></columns><rows><row rownum=\"1\"><cell columnname=\"page\" csv=\"http://www.ABC.com/profile/recipebox\">http://www.ABC.com/profile/recipebox</cell><cell columnname=\"events\" percentage=\"0.1%\">489</cell></row><row rownum=\"2\"><cell columnname=\"page\" csv=\"http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c\">http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c</cell><cell columnname=\"events\" percentage=\"0.0%\">380</cell></row></rows><totals><pagetotals><total columnname=\"events\" value=\"1820.00000\">1,820 (0.2%)</total></pagetotals><reporttotals><total columnname=\"events\" value=\"7838.000000\">7,838 (0.8%)</total></reporttotals><timeperiodtotals><total columnname=\"events\" value=\"955774.000000\">955,774 (100.0%)</total></timeperiodtotals></totals></xmlreport>";
static void Main(string[] args)
{
// parse from xml to objects
StringReader reader = new StringReader(starting);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(XmlReport));
var xmlreport = (XmlReport)xmlSerializer.Deserialize(reader);
// todo: do some process mapping ...
// parse out as json
var json = JsonConvert.SerializeObject(xmlreport);
Console.WriteLine(json);
Console.ReadLine();
}
}
[Serializable]
[XmlRoot(ElementName = "xmlreport")]
public class XmlReport
{
[XmlAttribute(AttributeName = "title")]
public string Title { get; set; }
[XmlAttribute(AttributeName = "dates")]
public string Dates { get; set; }
[XmlArray(ElementName = "columns")]
[XmlArrayItem(typeof(Column), ElementName = "column")]
public Collection<Column> Columns { get; set; }
}
[Serializable]
public class Column
{
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "type")]
public string Type { get; set; }
}
I've tried to parse the json to the original xml to begin with so appologies if I've not interpreted it properly. I've not done the entire structure but I hope the example above gives you an idea of how to do the rest.
Hope this helps.
One way of doing this is by getting the actual Data Structure of that JSON object that you have there.
Then create classes representing that data structure (if you can get a complete response -- having all properties, you just use this site to convert that to classes).
After that, deserialize that JSON object into your class using different libraries available. A sample could be this one.
Use this (JSon.NET) and a recursive function writes all keys and values to output window.
[TestMethod]
public void ParseMePlease()
{
string s = #"{""?xml"":{""#version"":""1.0"",""#encoding"":""iso-8859-1""},
""xmlreport"":{""#title"":""ABC: TEST Most Saved2"",""#dates"":""Week of May 19,2013"",
""columns"":{""column"":[{""#name"":""Page"",""#type"":""dimension"",""#text"":""Page""},{""#name"":""Events"",""#type"":""metric"",""#hastotals"":""true"",""#text"":""Events""}]},
""rows"":
{""row"":[{""#rownum"":""1"",""cell"":[{""#columnname"":""page"",""#csv"":""\""http://www.ABC.com/profile/recipebox\"""",""#text"":""http://www.ABC.com/profile/recipebox""},{""#columnname"":""events"",""#percentage"":""\""0.1%\"""",""#text"":""489""}]},
{""#rownum"":""2"",""cell"":[{""#columnname"":""page"",""#csv"":""\""http://www.ABC.com/recipes/peanut-butter-truffle-brownies/c5c602e4-007b-43e0-aaab-2f9aed89524c\"""",""#text"":""http://www.ABC.com/recip...c602e4-007b-43e0-aaab-2f9aed89524c""},{""#columnname"":""events"",""#percentage"":""\""0.0%\"""",""#text"":""380""}]}]},
""totals"":{""pagetotals"":{""total"":{""#columnname"":""events"",""#value"":""1820.000000"",""#text"":""1,820 (0.2%)""}},
""reporttotals"":{""total"":{""#columnname"":""events"",""#value"":""7838.000000"",""#text"":""7,838 (0.8%)""}},
""timeperiodtotals"":{""total"":{""#columnname"":""events"",""#value"":""955774.000000"",""#text"":""955,774 (100.0%)""}}}}}";
var result=JsonConvert.DeserializeObject<object>(s);
Debug.WriteLine("Right Click Result on quick watch for Result Views!(On Debug)"+result.ToString() );
JObject jobject = ((Newtonsoft.Json.Linq.JObject)result);
PrintDetail(jobject);
}
public void PrintDetail(JObject node)
{
foreach (var item in node)
{
Debug.WriteLine("Key:" + item.Key + " Value:" + item.Value);
if (item.Value is JObject)
{
PrintDetail((JObject)item.Value);
}
}
}

Read and parse a Json File in C#

How does one read a very large JSON file into an array in c# to be split up for later processing?
I have managed to get something working that will:
Read the file Miss out headers and only read values into array.
Place a certain amount of values on each line of an array. (So I
could later split it an put into 2d array)
This was done with the code below but it crashes the program after entering a few lines into the array. This might have to do with the file size.
// If the file extension was a jave file the following
// load method will be use else it will move on to the
// next else if statement
if (fileExtension == ".json")
{
int count = 0;
int count2 = 0;
int inOrOut = 0;
int nRecords=1;
JsonTextReader reader = new JsonTextReader(new StreamReader(txtLoaction.Text));
string[] rawData = new string[5];
while (reader.Read())
{
if (reader.Value != null)
if (inOrOut == 1)
{
if (count == 6)
{
nRecords++;
Array.Resize(ref rawData, nRecords);
//textBox1.Text += "\r\n";
count = 0;
}
rawData[count2] += reader.Value + ","; //+"\r\n"
inOrOut = 0;
count++;
if (count2 == 500)
{
MessageBox.Show(rawData[499]);
}
}
else
{
inOrOut = 1;
}
}
}
A snippet of the JSON I am working with is:
[
{ "millis": "1000",
"stamp": "1273010254",
"datetime": "2010/5/4 21:57:34",
"light": "333",
"temp": "78.32",
"vcc": "3.54" },
]
I need the values out of this JSON. For example, I need "3.54", but I would not want it to print the "vcc".
How can one read a JSON file in and only extract the data needed to be put into an array?
How about making everything easier with Json.NET?
public void LoadJson()
{
using (StreamReader r = new StreamReader("file.json"))
{
string json = r.ReadToEnd();
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
}
}
public class Item
{
public int millis;
public string stamp;
public DateTime datetime;
public string light;
public float temp;
public float vcc;
}
You can even get the values dynamically without declaring Item class.
dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
Console.WriteLine("{0} {1}", item.temp, item.vcc);
}
Doing this yourself is an awful idea. Use Json.NET. It has already solved the problem better than most programmers could if they were given months on end to work on it. As for your specific needs, parsing into arrays and such, check the documentation, particularly on JsonTextReader. Basically, Json.NET handles JSON arrays natively and will parse them into strings, ints, or whatever the type happens to be without prompting from you. Here is a direct link to the basic code usages for both the reader and the writer, so you can have that open in a spare window while you're learning to work with this.
This is for the best: Be lazy this time and use a library so you solve this common problem forever.
Answer for .NET Core
You can just use the built-in System.Text.Json instead of the 3rd-party Json.NET. To promote reuse, the JSON-file-reading functionality belongs in its own class and should be generic rather than hard-coded to a certain type (Item). Here's a full example:
using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
namespace Project
{
class Program
{
static async Task Main()
{
Item item = await JsonFileReader.ReadAsync<Item>(#"C:\myFile.json");
}
}
public static class JsonFileReader
{
public static async Task<T> ReadAsync<T>(string filePath)
{
using FileStream stream = File.OpenRead(filePath);
return await JsonSerializer.DeserializeAsync<T>(stream);
}
}
public class Item
{
public int millis;
public string stamp;
public DateTime datetime;
public string light;
public float temp;
public float vcc;
}
}
Or, if you prefer something simpler/synchronous:
class Program
{
static void Main()
{
Item item = JsonFileReader.Read<Item>(#"C:\myFile.json");
}
}
public static class JsonFileReader
{
public static T Read<T>(string filePath)
{
string text = File.ReadAllText(filePath);
return JsonSerializer.Deserialize<T>(text);
}
}
This can also be done in the following way:
JObject data = JObject.Parse(File.ReadAllText(MyFilePath));
string jsonFilePath = #"C:\MyFolder\myFile.json";
string json = File.ReadAllText(jsonFilePath);
Dictionary<string, object> json_Dictionary = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json);
foreach (var item in json_Dictionary)
{
// parse here
}
Based on #L.B.'s solution, the (typed as Object rather than Anonymous) VB code is
Dim oJson As Object = JsonConvert.DeserializeObject(File.ReadAllText(MyFilePath))
I should mention that this is quick and useful for constructing HTTP call content where the type isn't required. And using Object rather than Anonymous means you can maintain Option Strict On in your Visual Studio environment - I hate turning that off.
For any of the JSON parse, use the website http://json2csharp.com/ (easiest way) to convert your JSON into C# class to deserialize your JSON into C# object.
public class JSONClass
{
public string name { get; set; }
public string url { get; set; }
public bool visibility { get; set; }
public string idField { get; set; }
public bool defaultEvents { get; set; }
public string type { get; set; }
}
Then use the JavaScriptSerializer (from System.Web.Script.Serialization), in case you don't want any third party DLL like newtonsoft.
using (StreamReader r = new StreamReader("jsonfile.json"))
{
string json = r.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
var Items = jss.Deserialize<JSONClass>(json);
}
Then you can get your object with Items.name or Items.Url etc.
Very Easiest way I found on online to work with .JSON file in C#(or any other Programming Language)
Prerequisite:-
Install Newtonsoft.Json Library into your Project
Newtonsoft.Json
and here is the URL -> https://app.quicktype.io/
Steps
1> go to this URL - https://app.quicktype.io/
2> Copy and Paste your JSON file structure into Left sidebar
app.quicktype.io
3> Select required Language (here C#) from Options menu
4> Copy generated code and go to your Project and Create a new .cs file with the same name(here "Welcome.cs")
Welcome.cs
5> Paste all generated code into the newly created class.
Welcome.cs pasted Code
6> that's it. :)
Steps to Access value
1> Go to Main Program .cs file or wherever you need to access it.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Access Json values using Keys.>");
String jsonString = new StreamReader("give <.json> file Path here").ReadToEnd();
// use below syntax to access JSON file
var jsonFile = Welcome.FromJson(jsonString);
string FileName = jsonFile.File;
long Lvl = jsonFile.Level;
bool isTrue = jsonFile.CSharp;
Console.WriteLine(FileName);//JSON
Console.WriteLine(Lvl);//1
Console.WriteLine(isTrue);//true
}
}
For finding the right path I'm using
var pathToJson = Path.Combine("my","path","config","default.Business.Area.json");
var r = new StreamReader(pathToJson);
var myJson = r.ReadToEnd();
// my/path/config/default.Business.Area.json
[...] do parsing here
Path.Combine uses the Path.PathSeparator and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.
See https://stackoverflow.com/a/32071002/4420355
There is a faster way of parsing json then Json.Net . If you are using .net core 3.0 or up then you can use the System.Text.Json nuget package to serialize or deserialize.
you need to add:
using System.Text.Json
And then you can serialize as:
var jsonStr = JsonSerializer.Serialize(model);
And Deserialize as:
var model = JsonSerializer.Deserialize(jsonStr);
This code can help you:
string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
JObject data = JObject.Parse(_filePath );
There is an easier way to get JSON from file or from the Web:
Json.Net.Curl
Install-Package Json.Net.Curl
// get JObject from local file system
var json = Json.Net.Curl.Get(#"data\JObjectUnitTest1.json");
var json = await Json.Net.Curl.GetAsync(#"data\JObjectUnitTest1.json")
// get JObject from Server
var json = await Json.Net.Curl.GetAsync("http://myserver.com/data.json");
GitHub Project
Nuget
With Cinchoo ETL, an open source library, parsing of very large JSON file is iterative and simple to use
1. Dynamic Method: - No POCO class required
string json = #"
[
{
""millis"": ""1000"",
""stamp"": ""1273010254"",
""datetime"": ""2010/5/4 21:57:34"",
""light"": ""333"",
""temp"": ""78.32"",
""vcc"": ""3.54""
},
{
""millis"": ""2000"",
""stamp"": ""1273010254"",
""datetime"": ""2010/5/4 21:57:34"",
""light"": ""333"",
""temp"": ""78.32"",
""vcc"": ""3.54""
}
]
";
using (var r = ChoJSONReader.LoadText(json))
{
foreach (var rec in r)
Console.WriteLine(rec.Dump());
}
Sample fiddle: https://dotnetfiddle.net/mo1qvw
2. POCO Method:
Define POCO class matching json attributes
public class Item
{
public int Millis { get; set; }
public string Stamp { get; set; }
public DateTime Datetime { get; set; }
public string Light { get; set; }
public float Temp { get; set; }
public float Vcc { get; set; }
}
Then using the parser to load the JSON as below
string json = #"
[
{
""millis"": ""1000"",
""stamp"": ""1273010254"",
""datetime"": ""2010/5/4 21:57:34"",
""light"": ""333"",
""temp"": ""78.32"",
""vcc"": ""3.54""
},
{
""millis"": ""2000"",
""stamp"": ""1273010254"",
""datetime"": ""2010/5/4 21:57:34"",
""light"": ""333"",
""temp"": ""78.32"",
""vcc"": ""3.54""
}
]
";
using (var r = ChoJSONReader<Item>.LoadText(json))
{
foreach (var rec in r)
Console.WriteLine(ChoUtility.Dump(rec));
}
Sample fiddle: https://dotnetfiddle.net/fRWu0w
Disclaimer: I'm author of this library.

Deserialize JSON with C#

I'm trying to deserialize a Facebook friend's Graph API call into a list of objects. The JSON object looks like:
{"data":[{"id":"518523721","name":"ftyft"},
{"id":"527032438","name":"ftyftyf"},
{"id":"527572047","name":"ftgft"},
{"id":"531141884","name":"ftftft"},
{"id":"532652067","name"...
List<EFacebook> facebooks = new JavaScriptSerializer().Deserialize<List<EFacebook>>(result);
It's not working, because the primitive object is invalid. How can I deserialize this?
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
Sometimes I prefer dynamic objects:
public JsonResult GetJson()
{
string res;
WebClient client = new WebClient();
// Download string
string value = client.DownloadString("https://api.instagram.com/v1/users/000000000/media/recent/?client_id=clientId");
// Write values
res = value;
dynamic dyn = JsonConvert.DeserializeObject(res);
var lstInstagramObjects = new List<InstagramModel>();
foreach(var obj in dyn.data)
{
lstInstagramObjects.Add(new InstagramModel()
{
Link = (obj.link != null) ? obj.link.ToString() : "",
VideoUrl = (obj.videos != null) ? obj.videos.standard_resolution.url.ToString() : "",
CommentsCount = int.Parse(obj.comments.count.ToString()),
LikesCount = int.Parse(obj.likes.count.ToString()),
CreatedTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((double.Parse(obj.created_time.ToString()))),
ImageUrl = (obj.images != null) ? obj.images.standard_resolution.url.ToString() : "",
User = new InstagramModel.UserAccount()
{
username = obj.user.username,
website = obj.user.website,
profile_picture = obj.user.profile_picture,
full_name = obj.user.full_name,
bio = obj.user.bio,
id = obj.user.id
}
});
}
return Json(lstInstagramObjects, JsonRequestBehavior.AllowGet);
}
A great way to automatically generate these classes for you is to copy your JSON output and throw it in here:
http://json2csharp.com/
It will provide you with a starting point to touch up your classes for deserialization.
Very easily we can parse JSON content with the help of dictionary and JavaScriptSerializer. Here is the sample code by which I parse JSON content from an ashx file.
var jss = new JavaScriptSerializer();
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(json);
string _Name = sData["Name"].ToString();
string _Subject = sData["Subject"].ToString();
string _Email = sData["Email"].ToString();
string _Details = sData["Details"].ToString();
Newtonsoft.JSON is a good solution for these kind of situations. Also Newtonsof.JSON is faster than others, such as JavaScriptSerializer, DataContractJsonSerializer.
In this sample, you can the following:
var jsonData = JObject.Parse("your JSON data here");
Then you can cast jsonData to JArray, and you can use a for loop to get data at each iteration.
Also, I want to add something:
for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
var data = jsonData[i - 1];
}
Working with dynamic object and using Newtonsoft serialize is a good choice.
I agree with Icarus (would have commented if I could),
but instead of using a CustomObject class,
I would use a Dictionary (in case Facebook adds something).
private class MyFacebookClass
{
public IList<IDictionary<string, string>> data { get; set; }
}
or
private class MyFacebookClass
{
public IList<IDictionary<string, object>> data { get; set; }
}
Serialization:
// Convert an object to JSON string format
string jsonData = JsonConvert.SerializeObject(obj);
Response.Write(jsonData);
Deserialization::
To deserialize a dynamic object
string json = #"{
'Name': 'name',
'Description': 'des'
}";
var res = JsonConvert.DeserializeObject< dynamic>(json);
Response.Write(res.Name);
If you're using .NET Core 3.0, you can use System.Text.Json (which is now built-in) to deserialize JSON.
The first step is to create classes to model the JSON. There are many tools which can help with this, and some of the answers here list them.
Some options are http://json2csharp.com, http://app.quicktype.io, or use Visual Studio (menu Edit → Paste Special → Paste JSON as classes).
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Response
{
public List<Person> Data { get; set; }
}
Then you can deserialize using:
var people = JsonSerializer.Deserialize<Response>(json);
If you need to add settings, such as camelCase handling, then pass serializer settings into the deserializer like this:
var options = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var person = JsonSerializer.Deserialize<Response>(json, options);
You can use this extensions
public static class JsonExtensions
{
public static T ToObject<T>(this string jsonText)
{
return JsonConvert.DeserializeObject<T>(jsonText);
}
public static string ToJson<T>(this T obj)
{
return JsonConvert.SerializeObject(obj);
}
}
Here is another site that will help you with all the code you need as long as you have a correctly formated JSON string available:
https://app.quicktype.io/

Categories