Turn JSON into a C# List of objects - c#

Sorry, new to Json. Have read up but can't get this working. I have this json formatted string being returned on a .aspx page where I am using C#.
{"ContactsListResult":[{"Contact":"Fred Smith","ContactID":25},{"Contact":"Bill Wilson","ContactID":45}]}
I have a Contact object.
public class Contact
{
public string Contact { get; set; }
public int ContactID { get; set; }
}
I need to get each Contact into a Contact object and into a List of Contacts - just using whatever is built into Framework 4.0. I am not interested in the 'ContactsListResult' bit of the Json - I am just interested in the list of contacts within the square brackets.

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace ConsoleApplication1 {
class Program {
[Serializable]
public class ContactsListResult {
public string Contact { get; set; }
public int ContactID { get; set; }
} //
[Serializable]
public class CList {
public List<ContactsListResult> ContactsListResult = new List<ContactsListResult>();
} //
static void Main(string[] args) {
string s = "{\"ContactsListResult\":[{\"Contact\":\"Fred Smith\",\"ContactID\":25},{\"Contact\":\"Bill Wilson\",\"ContactID\":45}]}";
JavaScriptSerializer lSerializer = new JavaScriptSerializer();
CList lItems = lSerializer.Deserialize<CList>(s);
foreach (ContactsListResult lItem in lItems.ContactsListResult) Console.WriteLine(lItem.Contact + " " + lItem.ContactID);
Console.ReadLine();
} //
} // class
} // namespace
Please follow the details on my blog:
http://csharphardcoreprogramming.wordpress.com/2014/01/23/json-part-1-basics-follow-up-to-xml/
Bastian M.K. Ohta

DataContractJsonSerializer is the class you need to use. See here for a demo:
http://msdn.microsoft.com/en-us/library/hh674188.aspx
Also, google it. This took me 2 minutes of research.
Here's another stack overflow Q regarding the same item. Someone else recommends JSon.NET
Read JSON using DataContractJsonSerializer

You can use this library where you not have to decorate your clases without any Data Annotation... http://james.newtonking.com/json

Related

Deserialize Json from REST api and use the Values gotten from the Json

So when Working on a JSON Deserializer, I wanted to do something like this get the Values retrieved from a REST Webservice and made it into a Json Object.
So this works perfect, no troubles
So far, My the Json retrieved Looks like this :
{\"Fullname\":\"John Snow\",\"Telephone\":\"08147720192\",\"gender\":\"Male\",\"email\":\"john.snow#gmail.com\",\"date_ofbirth\":\"1985-06-22T00:00:00\",\"nationalID\":\"JS834788US\",\"accountnumber\":\"0034773291\",\"salary\":800000.00}
Now here is the worry, I would want to retrieve the values from a Deserialized Json and then Set the values, So it can be used in another application. I am building it in form of a Class Library.
Now like I said before I have been able to Make one, Which returns the Data into Json. Now i want to Deserialize and then use the values gotten from the REST api in another web application
The Code for the Deseializer looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Deserializer
{
public class EmpPersonalInfo
{
public string Fullname { get; set; }
public string Telephone { get; set; }
public string gender { get; set; }
public string email { get; set; }
public string date_ofbirth { get; set; }
public string nationalID { get; set; }
public string accountnumber { get; set; }
public decimal salary { get; set; }
}
public class RESTJSONDeserializer
{
public static void Deserializer(string JSON)
{
EmpPersonalInfo account = JsonConvert.DeserializeObject<EmpPersonalInfo>(JSON);
//Get and set the Values here
}
}
}
The primary challenge is I have never worked on something like this before. So for the sake of clarity, I would need some Explanation and guidance as to code something like this
Thanks
public class RESTJSONDeserializer
{
public static EmpPersonalInfo Deserializer(string JSON)
{
return JsonConvert.DeserializeObject<EmpPersonalInfo>(JSON);
//Get and set the Values here
}
}
this class should like this and when u need the deserialize object u can simply call this method
EmpPersonalInfo model= RESTJSONDeserializer.Deserializer("JsonFromApi");

Visual Studio C# How to parse and list each record/field of a json webservice

Below is the json text I receive for a test web service and looking for how it each record field could be displayed .
{"records":[
{"id":"10","email":"bcomecomaaacomea#myhost.om","name":"Dot"},{"id":"855","email":"webcastpoa0#myhost","name":"name_0"},{"id":"856","email":"webcastpoa1#myhost","name":"name_1"},{"id":"857","email":"webcastpoa2#myhost","name":"name_2"},{"id":"858","email":"webcastpoa3#myhost","name":"name_3"},{"id":"859","email":"webcastpoa4#myhost","name":"name_4"},{"id":"860","email":"webcastpoa5#myhost","name":"name_5"},{"id":"861","email":"webcastpoa6#myhost","name":"name_6"},{"id":"862","email":"webcastpoa7#myhost","name":"name_7"},{"id":"863","email":"webcastpoa8#myhost","name":"name_8"},{"id":"864","email":"webcastpoa9#myhost","name":"name_9"},{"id":"865","email":"webcastpoa10#myhost","name":"name_10"},{"id":"866","email":"webcastpoa11#myhost","name":"name_11"},{"id":"867","email":"webcastpoa12#myhost","name":"name_12"},{"id":"868","email":"webcastpoa13#myhost","name":"name_13"},{"id":"869","email":"webcastpoa14#myhost","name":"name_14"},{"id":"870","email":"webcastpoa15#myhost","name":"name_15"},{"id":"871","email":"webcastpoa16#myhost","name":"name_16"},{"id":"872","email":"webcastpoa17#myhost","name":"name_17"},{"id":"873","email":"webcastpoa18#myhost","name":"name_18"},{"id":"874","email":"webcastpoa19#myhost","name":"name_19"},{"id":"875","email":"webcastpoa20#myhost","name":"name_20"},{"id":"876","email":"webcastpoa21#myhost","name":"name_21"},{"id":"877","email":"webcastpoa22#myhost","name":"name_22"},{"id":"878","email":"webcastpoa23#myhost","name":"name_23"},{"id":"879","email":"webcastpoa24#myhost","name":"name_24"},{"id":"880","email":"webcastpoa25#myhost","name":"name_25"},{"id":"881","email":"webcastpoa26#myhost","name":"name_26"},{"id":"882","email":"webcastpoa27#myhost","name":"name_27"},{"id":"883","email":"webcastpoa28#myhost","name":"name_28"},{"id":"884","email":"webcastpoa29#myhost","name":"name_29"},{"id":"885","email":"webcastpoa30#myhost","name":"name_30"},{"id":"886","email":"webcastpoa31#myhost","name":"name_31"},{"id":"887","email":"webcastpoa32#myhost","name":"name_32"},{"id":"888","email":"webcastpoa33#myhost","name":"name_33"},{"id":"889","email":"webcastpoa34#myhost","name":"name_34"},{"id":"890","email":"webcastpoa35#myhost","name":"name_35"},{"id":"891","email":"webcastpoa36#myhost","name":"name_36"},{"id":"892","email":"webcastpoa37#myhost","name":"name_37"},{"id":"893","email":"webcastpoa38#myhost","name":"name_38"},{"id":"894","email":"webcastpoa39#myhost","name":"name_39"},{"id":"895","email":"webcastpoa40#myhost","name":"name_40"},{"id":"896","email":"webcastpoa41#myhost","name":"name_41"},{"id":"897","email":"webcastpoa42#myhost","name":"name_42"},{"id":"898","email":"webcastpoa43#myhost","name":"name_43"},{"id":"899","email":"webcastpoa44#myhost","name":"name_44"}
]}
I have the following code so far.
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Net;
using System.IO;
using Newtonsoft.Json;
WebClient client = new WebClient();
string reply = client.DownloadString("http://192.168.1.115/php_poa/test_select.php");
MessageBox.Show(reply);
records p1 = JsonConvert.DeserializeObject<records>(reply);
MessageBox.Show(p1.ToString());
class records
{
public string id { get; set; }
public string email { get; set; }
public string name { get; set; }
}
And would like a for loop to process each record.
THanks
Just use List<record> instead. You won't require to iterate it through loop.
Example:
List<records> p1 = JsonConvert.DeserializeObject<List<records>>(reply);
Remember to add following namespace at top
using System.Collection.Generic;
You need to use next class for deserialization:
class MyResponse
{
public List<Records> Records { get; set; }
}
class Records
{
public string Id { get; set; }
public string Email { get; set; }
public string Name { get; set; }
}
And now you can deserialize your web response:
MyResponse myResponse = JsonConvert.DeserializeObject<MyResponse>(reply);
to iterate through a loop you can do something like this
JObject records = JObject.Parse(json);
foreach (var record in obj["records"])
{
records p1 = JsonConvert.DeserializeObject<records>(reply);
}
although i would suggest creating a constructor for your class instead of using DeserializeObject
like this
public Records(JToken toekn)
{
Id = (string)toekn["Id "];
Email = (string)toekn["Email "];
Name = (string)toekn["Name "];
}
and use
Records record = new Records(record) instead of DeserializeObject inside the loop

Creating object to represent XML data using C#

below is the XML code.
<Shops>
<Shop>
<Location>INDIA</Location>
<Id>123</Id>
<ShopLists>
<ShopList>
<Area>500sqft</Area>
<Name>Home Decor</Name>
<LicenseNo>Ab123</LicenseNo>
</ShopList>
<ShopList>
<Area>1000sqft</Area>
<LicenseNo>Ab123</LicenseNo>
</ShopList>
</ShopLists>
</Shop>
</Shops>
Creating an object with C# using Linq is finding challenging here as one of the data is missing in 'shoplist' and structure is nested. reply if find some inputs on this.
I encourage you to look at http://xmltocsharp.azurewebsites.net/ put your xml and you will be able to convert your xml representation into C# classes.
you can then use XmlSerializer to deserialize your xml into specific type as exemplified in here.
Hope that helps.
I always use XmlSerializer with objects to perform such tasks.
Reference Assembly System.Xml.Serialization
using System.Xml.Serialization;
First create the object model:
[XmlRoot("Shops")]
public class XmlShops
{
[XmlElement("Shop",typeof(Shop))]
public List<Shop> Shops { get; set; }
}
public class Shop
{
[XmlElement("Location")]
public string Location { get; set; }
[XmlElement("Id")]
public string Id { get; set; }
[XmlArray("ShopLists")]
[XmlArrayItem("ShopList",typeof(ShopList))]
public List<ShopList> ShopLists { get; set;}
}
public class ShopList
{
[XmlElement("Area")]
public string Area { get;set; }
[XmlElement("Home")]
public string Home { get;set; }
[XmlElement("LicenseNo")]
public string LicenseNo { get;set; }
}
Afterwards use the Serializer to get the xml data into the object model:
XmlSerializer ser = new XmlSerializer(typeof(XmlShops));
using (StreamReader sr = new StreamReader(#"d:\tmp\test.xml"))
{
XmlShops data = (XmlShops)ser.Deserialize(sr);
// xml should be serialized to your object model into data.
}

C# JSON deserializing to Custom Class

I would like to deserialize a JSON object like this:
[{"Response":"OK","UUID":"89172"},{"Response":"OK","UUID":"10304"}]
into a custom class where it has variables storing Response and UUID. However I would want to deserialize multiple data response such as above example. It will be great if I can use the method ForEach such that I can pop the data out accordingly. Can anyone advise? Many Thanks!
write this class
public class MyClass
{
public string Response { get; set; }
public string UUID { get; set; }
}
then you can deserialize it using the library newtonsoft.json
string jsonString = "[{"Response":"OK","UUID":"89172"},{"Response":"OK","UUID":"10304"}]";
...
...
var myListOfItems= JsonConvert.DeserializeObject<List<MyClass>>(jsonString);
foreach(var item in myListOfItems)
{
....
}
FULL CODE IN CONSOLE APPLICATION
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string jsonString = "[{'Response':'OK','UUID':'89172'},{'Response':'OK','UUID':'10304'}]";
var items= JsonConvert.DeserializeObject<List<MyClass>>(jsonString);
foreach (var item in items)
{
Console.WriteLine("UUUID: "+item.UUID);
Console.WriteLine("Response: " + item.Response);
Console.WriteLine();
}
Console.ReadKey();
}
}
public class MyClass
{
public string Response { get; set; }
public string UUID { get; set; }
}
}
I would use Json.Net for that.
Have a look at Json.Net help in the "Serializing and Deserializing JSON" section.
There they show you how to deserialize the json-string into an object.
You will need Newtonsoft.Json library for this to work:
public class A
{
public string Response { get; set; }
public string UUID { get; set; }
}
static void Main(string[] args)
{
var json = "[{\"Response\":\"OK\",\"UUID\":\"89172\"}, \"Response\":\"OK\",\"UUID\":\"10304\"}]";
var result = JsonConvert.DeserializeObject<IEnumerable<A>>(json);
foreach (var a in result)
Console.WriteLine("Response: {0} UUID: {1}", a.Response, a.UUID);
Console.ReadKey();
}
I've finally resolved this problem thanks with the help of #Newton Sheikh. Thank you first of all.
First I created a class (Student)
public class Student
{
public string Response { get; set; }
public string UUID { get; set; }
}
Then I imported the JSON.NET and created a function:
public List<Student> ReturnAllStudentsList()
{
string jsonString = "[{'Response':'OK','UUID':'89172'},{'Response':'OK','UUID':'10304'}]";
List<Student> Students = new List<Student>(); //Creates a list of custom Type: Student
var result = JsonConvert.DeserializeObject<List<Student>>(jsonString);
foreach (var student in result)
{
Students.Add(student);
}
return Students;
}
From this point, I have a list of Students. Then in my main program, I call this function:
private void button1_Click(object sender, EventArgs e)
{
List<Student> Students = ReturnAllStudentsList(); // Gets the list from JSON.
foreach(Student student in Students)
{
// Here I can access to each student for every loop cycle.
MessageBox.Show(student.Response);
}
}
Thank you #Newton Sheikh and others help! I hope this example code can help others too! Cheers.

retrieve table from a web service to wp7 page

Is there any way to retrieve a table from a web service to a wp7 app page as its?
i just wanna sth easy to use than making a table each time getting data
Have look on MSDN for System.Xml namespace. It contains lot of usable classes. You should use XmlReader or something similair to load it to array or generic collection. Hope this helps, 'cause bit unclear question.
EDIT:
This is the code what have I done for loading sample data to generic collection:
Sample data:
<?xml version="1.0" encoding="utf-8" ?>
<studentPunishmentsTables>
<studentPunishmentsTable>
<fromSemester/>
<fromSemesterDesc/>
<issueDate>01/04/2012</issueDate>
<note/>
<penalty>Course Failure</penalty>
<semester>311</semester>
<semesterDesc>First Semester 31/32</semesterDesc>
<toSemester/>
<toSemesterDesc/>
</studentPunishmentsTable>
<studentPunishmentsTable>
<fromSemester/>
<fromSemesterDesc/>
<issueDate>01/04/2012</issueDate>
<note/>
<penalty>Semester Failure</penalty>
<semester>311</semester>
<semesterDesc>First Semester 31/32</semesterDesc>
<toSemester/>
<toSemesterDesc/>
</studentPunishmentsTable>
</studentPunishmentsTables>
Code:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
namespace XMLStudent
{
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("st.xml");
List<StudentPunishment> sp = new List<StudentPunishment>();
foreach (XmlNode nod in doc.SelectNodes(#"studentPunishmentsTables/studentPunishmentsTable"))
{
StudentPunishment s = new StudentPunishment();
s.FromSemester = nod.ChildNodes[0].InnerText;
s.FromSemesterDesc = nod.ChildNodes[1].InnerText;
s.IssueDate = nod.ChildNodes[2].InnerText;
s.Note = nod.ChildNodes[3].InnerText;
s.Penalty = nod.ChildNodes[4].InnerText;
s.Semester = nod.ChildNodes[5].InnerText;
s.SemesterDesc = nod.ChildNodes[6].InnerText;
s.ToSemester = nod.ChildNodes[7].InnerText;
s.ToSemesterDesc = nod.ChildNodes[8].InnerText;
sp.Add(s);
}
Console.WriteLine(sp[0].IssueDate);
Console.Read();
}
}
class StudentPunishment
{
public string FromSemester { get; set; }
public string FromSemesterDesc { get; set; }
public string IssueDate { get; set; }
public string Note { get; set; }
public string Penalty { get; set; }
public string Semester { get; set; }
public string SemesterDesc { get; set; }
public string ToSemester { get; set; }
public string ToSemesterDesc { get; set; }
}
}
So. This code is loading XMLDocument with sample data and it's selecting data of each studentPunishmentsTable into new object of StudentPunishment class. There're properties for holding that data. After everything is done and object of student's punishment is added into generic collection ('List'), code is trying to show date of first object in collection. You can test is yourself, it's working for me.

Categories

Resources