I want to deserialise the following Json. I have tried the following:
JSON Data:
{
"data":[
{
"employee":[
{
"empdetails":[
{
"empid":"40",
"empname":"Amit",
"empdept":"Director",
"empphone":[
{
"home":"23432235",
"office":"2352353",
}]
},
{
"empid":"54",
"empname":"Abhishek",
"empdept":"HR",
"empphone":[
{
"home":"5445457",
"office":"34634634",
}]
},
{
"empid":"80",
"empname":"Rahul",
"empdept":"Finance"
},
{
"empid":"71",
"empname":"Anand",
"empdept":"Marketing",
"empphone":[
{
"home":"46346346",
"office":"346346346",
}]
}]
}],
}
Code:
using System;
using Newtonsoft.Json.linq;
using System.Collections.Generics;
class Program
{
public class emp
{
public int empid {get; set;}
public string empname {get; set;}
public string empdept {get; set;}
public string empcontact {get; set; }
}
static void main(string[] args)
{
WebClient c= new WebClient();
var json = c.DownloadString(new uri("sampleurl"));
dynamic dynamicObj=JsonConvert.DeserializeObject(json);
foreach (var data in dynamicObj.data)
{
foreach (var getempdet in data.employee)
{
foreach(var dat in getempdet)
{
foreach(var datas in dat)
{
foreach(var getempdetails in datas)
{
foreach(var finaldata in getempdetails)
{
Console.WriteLine("\t{0}", finaldata);
List<emp> empList=newList<emp>();
}
}
}
}
}
}
Console.ReadLine();
}
}
Create C# classes that map to your json. As below:
public class Data
{
public List<Employee> Employees { get; set; }
}
public class Employee
{
public List<EmpDetails> EmpDetailss { get; set; }
}
public class EmpDetails
{
public int Empid { get; set; }
public string Empname { get; set; }
public string Empdept { get; set; }
public EmpPhone EmpPhone{ get; set; }
}
public class EmpPhone
{
public string Home { get; set; }
public string Office { get; set; }
}
and then
WebClient c = new WebClient();
var json = c.DownloadString("sampleurl");
Data data = JsonConvert.DeserializeObject<Data>(json);
Related
I Get json data from third party in json format.
I am trying to fetch RollId from "Id" and MType from "Data" in some cases
"Data" doesn't have fields it is kind of blank.
It's working when we have "Data". In case of blank it's not working.
any idea on this? Is there a better approach of doing this?
This is the Json
string json = #"{
'root': {
'_type': '_container',
'Class': '.key.PModel',
'Elements': {
'_type': 'array<element>',
'_data': [
{
'_type': 'element',
'Class': '.key.PElement',
'Id': {
'_type': 'testId',
'Class': '.key.PModel',
'RollId': '.key.7157'
},
'Data': {
'_type': 'p_model',
'Class': '.key.Unsupported',
'MType': '.TestMType',
'Version': {
'_type': 'test__version',
'Class': '.key.TestVersion',
}
}
},
{
'_type': 'element',
'Class': '.key.PElement',
'Id': {
'_type': 'TestId',
'Class': '.key.PModel',
'RollId': '.key.11261'
},
'Data': '.ref.root.Elements.0.Data'
},
{
'_type': 'element',
'Class': '.key.PElement',
'Id': {
'_type': 'TestId',
'Class': '.key.PModel',
'RollId': '.key.7914'
},
'Data': '.ref.root.Elements.0.Data'
}
]
}
}
}";
This is the Code
public class Program
{
static void Main(string[] args)
{
//it provide json
var testCont = thirdpartyapi();
var dataList = new List<TestResponse>();
foreach (var testData in testCont.Elements())
{
var data = new TestResponse();
data.col1 = Convert.ToInt32(testData.Id().RollId());
data.col2 = testData.Data().MType().ToString();
dataList.Add(data);
}
}
public class TestResponse
{
public int col1 { get; set; }
public string col2 { get; set; }
}
}
First, try to get a valid well-formed json. You can use this code beautify tool. Then you can automatically generate C# class using json2csharp. Finally as you have C# class you can apply if statements and check if property is null.
Generated C# wrapper:
public class Id
{
public string _type { get; set; }
public string Class { get; set; }
public string RollId { get; set; }
}
public class Datum
{
public string _type { get; set; }
public string Class { get; set; }
public Id Id { get; set; }
public object Data { get; set; }
}
public class Elements
{
public string _type { get; set; }
public List<Datum> _data { get; set; }
}
public class Root
{
public string _type { get; set; }
public string Class { get; set; }
public Elements Elements { get; set; }
}
public class RootObject
{
public int encoding_version { get; set; }
public Root root { get; set; }
}
If you want to pick only few fields from complex JSON, you can consider using Cinchoo ETL - an open source library
Sample below shows how to pick RollId and MType values from your json
using (var r = new ChoJSONReader("## YOUR JSON FILE PATH ##")
.WithJSONPath("$.._data")
.WithField("RollId", jsonPath: "$..Id.RollId", fieldType: typeof(string))
.WithField("MType", jsonPath: "$..Data.MType", fieldType: typeof(string))
)
{
foreach (var rec in r)
{
Console.WriteLine((string)rec.RollId);
Console.WriteLine((string)rec.MType);
}
}
Hope it helps.
The easiest way is use the DataContractJsonSerializer
Here you can read more about it.
All in all you need to create a model which has the same possible outcome as your json.
Then you can just use the DataContractJsonSerializer to create an object of you model by using a MemoryStream.
Here you can find a nice tool to create the model from the JSON.
For example this one:
public class Id
{
public string _type { get; set; }
public string Class { get; set; }
public string RollId { get; set; }
}
public class Datum
{
public string _type { get; set; }
public string Class { get; set; }
public Id Id { get; set; }
public object Data { get; set; }
}
public class Elements
{
public string _type { get; set; }
public List<Datum> _data { get; set; }
}
public class Root
{
public string _type { get; set; }
public string Class { get; set; }
public Elements Elements { get; set; }
}
public class RootObject
{
public int encoding_version { get; set; }
public Root root { get; set; }
}
Then you use the MemoryStream and the DataContractJsonSerializer to Create an object of RootObject from that JSON.
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
stream1.Position = 0;
RootObject rootObject = (RootObject)ser.ReadObject(stream1);
And yes, as Adriani6 mentiones - your JSON is invalid at this point:
"Data": {
"_type": "p_model",
"Class": ".key.Unsupported",
"MType": ".TestMType",
"Version": {
"_type": "test__version",
"Class": ".key.TestVersion",
}
There is a , at the end wich is not allowed.
I started to learn C# and some Json, I am trying to get this form of Json format:
Desired Output :
I have tried this:
static void Main(string[] args)
{
var myjason = new myJson
{
ContentDisposition = "",
md5 = "da855ff838250f45d528a5a05692f14e",
file_name = "MyFile.docx",
features = new[] { "te" },
te = new te { reports = new[] { "pdf", "xml" } },
// images = new img { { a.id = "7e6fe36e-889e-4c25-8704-56378f0830df", a.revision = 1 }, { a.id = "e50e99f3-5963-4573-af9e-e3f4750b55e2", a.revision = 1 } }
};
string json = JsonConvert.SerializeObject(myjason, Formatting.Indented);
Console.WriteLine(json);
}
public class myJson
{
public string ContentDisposition{ get; set; }
public string md5 { get; set; }
public string file_name { get; set; }
public string[] features { get; set; }
public te te { get; set; }
public img images { get; set; }
}
public class a
{
public string id { get; set; }
public int revision { get; set; }
}
public class te
{
public string[] reports { get; set; }
}
public class img
{
public a[] images { get; set; }
}
And here is my current output:
Current output:
Please help, thanks a lot!
I think you are a bit confused about what's going on here. It looks like you're trying to POST some JSON to some endpoint.
Content-Disposition and Content-Type are HTTP headers. They are not JSON.
The JSON starts with the first { and this is the body of the POST. To create that body, you could use a C# object like:
public class MyJson {
public class MyRequest request {get ;set;}
}
public class MyRequest {
public string md5 {get;set;}
public string file_name {get;set;}
public string file_type {get;set;}
public List<string> features {get;set;}
public MyTe te {get;set;}
}
public class MyTe {
public List<string> reports {get;set;}
public List<MyImages> images {get;set;}
}
public class MyImages {
public string id {get;set;}
public int revision {get;set;}
}
And then use JsonConvert.SerializeObject on a MyJson object. To set the HTTP headers depends on what you're trying to do and with which tools, and that probably belongs in a different question.
EDIT: I said "and so on" because it's really just a rote exercise, and there are better tools to do this but I've updated.
Content-Disposition and Content-Type are request headers so they don't need to be in your json body
Here I've also demostrated how you can set a custom json property name using JsonProperty attribute.
static void Main(string[] args)
{
var myjason = new myJsonClass
{
Request = new requestClass
{
md5 = "da855ff838250f45d528a5a05692f14e",
file_name = "MyFile.docx",
file_type = "docx",
features = new[] { "te" },
te = new te
{
reports = new[] { "pdf", "xml" },
images = new a[] { new a { id = "7e6fe36e-889e-4c25-8704-56378f0830df", revision = 1 }, new a { id = "e50e99f3-5963-4573-af9e-e3f4750b55e2", revision = 1 } }
},
}
};
string json = JsonConvert.SerializeObject(myjason, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
public class myJsonClass
{
[JsonProperty("request")]
public requestClass Request { get; set; }
}
public class requestClass
{
public string md5 { get; set; }
public string file_name { get; set; }
public string file_type { get; set; }
public string[] features { get; set; }
public te te { get; set; }
}
public class a
{
public string id { get; set; }
public int revision { get; set; }
}
public class te
{
public string[] reports { get; set; }
public a[] images { get; set; }
}
Output:
{
"request": {
"md5": "da855ff838250f45d528a5a05692f14e",
"file_name": "MyFile.docx",
"file_type": "docx",
"features": [
"te"
],
"te": {
"reports": [
"pdf",
"xml"
],
"images": [
{
"id": "7e6fe36e-889e-4c25-8704-56378f0830df",
"revision": 1
},
{
"id": "e50e99f3-5963-4573-af9e-e3f4750b55e2",
"revision": 1
}
]
}
}
}
I'm using the Newtonsoft library for parsing JSON:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
I have my json string and "MyClass" class.
JSON string:
{
"Result":
{
"MyClassList": [
{"Id":1,"Amount":"5,00"},
{"Id":2,"Amount":"10,00"},
{"Id":3,"Amount":"20,00"},
{"Id":4,"Amount":"25,00"}
]
"ReturnValues":
{
"ErrorCode":1,
"ErrorDescription":"Successful"
}
}
}
My Class:
public class MyClass
{
[JsonProperty("Id")]
Int64 Id { get; set; }
[JsonProperty("Amount ")]
string Amount { get; set; }
}
I am getting json data using these classes "GetMyClassList", "RootObject" and "ReturnValues".
List<MyClass> GetMyClassList()
{
JObject jo = new JObject();
List<MyClass> myClassList = new List<MyClass>();
jo.Add("Name", "Name");
jo.Add("Surname", "Surname");
url = "MyUrl";
string responseText = ExecuteHttpRequest(url , "POST",
"application/json", Encoding.UTF8.GetBytes(jo.ToString()), 3000);
myClassList = JsonConvert.DeserializeObject<RootObject>(responseText)
.GetMyClassListResult.MyClassList;
return myClassList;
}
public class ReturnValues
{
public int ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
public class GetMyClassListResult
{
[JsonProperty("MyClassList")]
public List<MyClass> MyClassList { get; set; }
public ReturnValues ReturnValues { get; set; }
}
public class RootObject
{
public GetMyClassListResult GetMyClassListResult { get; set; }
}
I cannot get this data array (Id and amount).
and I want to take this data and show it in a dataGridView.
The best way to t-shoot this is set breakpoint at the line, where u getting the results from method -> is it filled? This Line:
return myClassList;
I have run Your code with single adjustment -> I have just used the direct JSON (not from web) - code below. This run without issues and I can see all the results parsed out of the JSON.
You have to find if the issue is parsin the JSON, or setting the data to the DataGridTable (which code You have not included at all).
class Program
{
static void Main(string[] args)
{
var result = new Program().GetMyClassList();
foreach (var item in result)
Console.WriteLine($"ID: {item.Id}\tAmount:{item.Amount}");
Console.ReadKey();
}
public List<MyClass> GetMyClassList()
{
List<MyClass> myClassList = new List<MyClass>();
string responseText = "{\"GetMyClassListResult\":{\"MyClassList\":[{\"Id\":1,\"Amount\":\"5,00\"},{\"Id\":2,\"Amount\":\"10,00\"},{\"Id\":3,\"Amount\":\"20,00\"},{\"Id\":4,\"Amount\":\"25,00\"}],\"ReturnValues\":{\"ErrorCode\":1,\"ErrorDescription\":\"Successful\"}}}";
myClassList = JsonConvert.DeserializeObject<RootObject>(responseText)
.GetMyClassListResult.MyClassList;
return myClassList;
}
}
public class MyClass
{
[JsonProperty("Id")]
public Int64 Id { get; set; }
[JsonProperty("Amount")]
public string Amount { get; set; }
}
public class ReturnValues
{
public int ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
public class GetMyClassListResult
{
[JsonProperty("MyClassList")]
public List<MyClass> MyClassList { get; set; }
public ReturnValues ReturnValues { get; set; }
}
public class RootObject
{
public GetMyClassListResult GetMyClassListResult { get; set; }
}
The JSON string contains a whitespace in the Resource Objects so 'id' is filled, but 'use id' 'userstatus' 'last event' are null.
I tried 3 different ways in my class but none of them works()
Underscore
With whitespace
Without whitespace
My code(c#):
this is the JSON string
{
"resultsList":[
{
"id":"1",
"last event":"Mar 20 07:08 AM",
"use id":"142AD",
"user status":"offline"
},
{
"id":"2",
"last event":"Mar 19 08:07 AM",
"use id":"1426BD",
"user status":"offline"
}
]
}
I Deserialize the JSON in
Results.cs(form)
string url = "API url";
var json = new WebClient().DownloadString(url);
var results = JsonConvert.DeserializeObject<Rootobject>(json);
Sessions.cs(class)
public class Rootobject
{
public Resultslist[] resultsList { get; set; }
}
public class Resultslist
{
public int id { get; set; }
public string last event { get; set; }
public string use_id { get; set; }
public string userstatus { get; set; }
}
The simplest approach in your case would be:
string json = "{\"resultsList\":[{\"id\":\"1\",\"last event\":\"Mar 20 07:08 AM\",\"use id\":\"142AD\",\"user status\":\"offline\"},{\"id\":\"2\",\"last event\":\"Mar 19 08:07 AM\",\"use id\":\"1426BD\",\"user status\":\"offline\"}]}";
dynamic o = JsonConvert.DeserializeObject(json);
var result = o["resultsList"][0]["last event"];
Try this:
using System;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var json = #"{""resultsList"":[{ ""id"":""1"",""last_event"":""Mar 20 07:08 AM"",""use_id"":""142AD"",""user_status"":""offline""}, { ""id"":""2"",
""last_event"":""Mar 19 08:07 AM"",
""use_id"":""1426BD"",
""user_status"":""offline""
}
]
}";
var results = JsonConvert.DeserializeObject<Rootobject>(json);
for (int i = 0; i < results.resultsList.Length; i++)
{
Console.WriteLine("Id:" + results.resultsList[i].id);
Console.WriteLine("Last Event:" + results.resultsList[i].last_event);
Console.WriteLine("User ID:" + results.resultsList[i].use_id);
Console.WriteLine("User Status:" + results.resultsList[i].user_status);
}
Console.ReadKey();
}
}
public class Rootobject
{
public Resultslist[] resultsList { get; set; }
}
public class Resultslist
{
public int id { get; set; }
public string last_event { get; set; }
public string use_id { get; set; }
public string user_status { get; set; }
}
}
Sessions.cs(class)
I added a JsonProperty and it works.
public class Rootobject
{
public Resultslist[] resultsList { get; set; }
}
public class Resultslist
{
public int id { get; set; }
[JsonProperty("last event")]
public string lastevent { get; set; }
[JsonProperty("use id")]
public string useid { get; set; }
[JsonProperty("user status")]
public string userstatus { get; set; }
}
I am facing a problem for parsing a JSON array in C#
{
"details" : [{
"state" : "myState1",
"place" : [{
"name" : "placeName",
"age" : 13
}
]
}, {
"state" : "myState2",
"place" : [{
"name1" : "placeName"
}
]
}, {
"state" : "myState3",
"place" : [{
"name2" : "placeName"
}
]
}
]
}
My code is:
static void Main(string[] args)
{
string txt = File.ReadAllText("MyJSONFile.txt");
JavaScriptSerializer ser = new JavaScriptSerializer();
var data = ser.Deserialize(txt);
}
public class Wrap
{
public List<Dictionary<string, object>> details { get; set; }
}
How can I read data from these dictionaries? Sometimes the JSON will include only 1 facility's details, but other times there are more than 30 items in the array. This data is being pulled from the database.
You may use the following C# classes structure:
public class Place
{
public string name { get; set; }
public int age { get; set; }
public string name1 { get; set; }
public string name2 { get; set; }
}
public class Detail
{
public string state { get; set; }
public List<Place> place { get; set; }
}
public class Root
{
public List<Detail> details { get; set; }
}
public class Program
{
static void Main(string[] args)
{
string txt = File.ReadAllText("MyJSONFile.txt");
JavaScriptSerializer ser = new JavaScriptSerializer();
var data = ser.Deserialize<Root>(txt);
Console.WriteLine(data.details.Count); // 3
Console.WriteLine(data.details[0].state); // myState1
Console.WriteLine(data.details[1].place.Count); // 1
Console.WriteLine(data.details[1].place[0].age); // 13
}
}
The class structure you are using is wrong.
You will have to use the structure as follows, which corresponds to your JSON.
This structure have been generated using json2csharp
public class Place
{
public string name { get; set; }
public int age { get; set; }
public string name1 { get; set; }
public string name2 { get; set; }
}
public class Detail
{
public string state { get; set; }
public List<Place> place { get; set; }
}
public class RootObject
{
public List<Detail> details { get; set; }
}
Now in your code you can de serialize this using Newtonsoft.Json as follows:
static void Main(string[] args)
{
string jsonText = System.IO.File.ReadAllText("MyJSONFile.txt");
var rootObj = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonText);
rootObj.details.ForEach(detail =>
{
Console.WriteLine(detail.state);
detail.place.ForEach(p =>
{
if (string.IsNullOrWhiteSpace(p.name) == false)
{
Console.WriteLine(p.name);
}
if (string.IsNullOrWhiteSpace(p.name1) == false)
{
Console.WriteLine(p.name1);
}
if (string.IsNullOrWhiteSpace(p.name2) == false)
{
Console.WriteLine(p.name2);
}
if (p.age > 0)
{
Console.WriteLine(p.age);
}
Console.WriteLine(string.Empty);
});
});
Console.ReadKey(true);
}