How to Convert Json Object to Array in C# - c#

I am trying to convert a JSON object in to C# array.
this is the JSon I Getfrom the Server webrequest response:
string result = sr.ReadToEnd(); // this line get me response
result = {
"subjects": [{
"subject_id": 1,
"subject_name": "test 1",
"subject_class": 4,
"subject_year": "2015",
"subject_code": "t-1"
},{
"subject_id": 2,
"subject_name": "test 2",
"subject_class": 5,
"subject_year": "",
"subject_code": "t-2"
}]
};
dynamic item = JsonConvert.DeserializeObject<object>(result);
string iii = Convert.ToString(item["subjects"]);
I want to Get the Subjects and Save them in Array so i can use them for other purpose.
I use these to Method but always got the empty values.
List<subjects> subject1 = (List<subjects>)JsonConvert.DeserializeObject(iii, typeof(List<subjects>));
and
subjects[] subject2 = JsonConvert.DeserializeObject<subjects[]>(iii);
Please Help Me to Solve this.
And my Subject Class is..
class subjects
{
public int id { get; set; }
public string name { get; set; }
public int class_name { get; set; }
public string year { get; set; }
public string code { get; set; }
}

The property names won't match as is, because you subjects class don't have the 'subject_' prefix the JSON object has. Easiest fix is to change your property names as shown in Ali's answer. Just in case you need to keep your property names as is, you can also use a JsonProperty attribute to alter the serialization names (perhaps there's a more generic way using some sort of converter, but didn't think the amount of properties needed it)
class subjects
{
[JsonProperty("subject_id")]
public int id { get; set; }
[JsonProperty("subject_name")]
public string name { get; set; }
[JsonProperty("subject_class")]
public int class_name { get; set; }
[JsonProperty("subject_year")]
public string year { get; set; }
[JsonProperty("subject_code")]
public string code { get; set; }
}
If you never need the root subjects you can also skip it without dynamic or an extra class with something like:
subjects[] arr = JObject.Parse(result)["subjects"].ToObject<subjects[]>();
(JObject is part of the namespace Newtonsoft.Json.Linq )

You need to create a structure like this:
public class Subjects
{
public List<Subject> subjects {get;set;}
}
public class Subject
{
public string subject_id {get;set;}
public string subject_name {get;set;}
}
Then you should be able to do:
Subjects subjects = JsonConvert.DeserializeObject<Subject>(result);

Related

How to Convert JSON object to Array

I am new to C# need help to convert json Object to Array
convert this json
[
{
"Id": 1000,
"Name": "May",
"Address": "odyssey",
"Country": "USA",
"Phone": "12345"
}
]
To
var details = {1000,May,odyssey,USA,12345};
Use Newtonsoft.Json to deserialize JSON to a specified .net type. You can deserialize to a class too, see below:
public class Person
{
public int Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public string Phone {get;set;}
}
var details = JsonConvert.DeserializeObject<Person>(json);
You are going to have to deserialize the Json String. Deserialize into array of objects.
JavaScriptSerializer js = new JavaScriptSerializer();
yourClass[] items = js.Deserialize<Yourclass[]>(yourJSONcontent);
Steps:
1. Create Model.
2. Get Data in string
3.Deserialize Object
And if you are confused How to create C# model from the json then use this link.
https://app.quicktype.io
Use This Model.
public class Test
{
[JsonProperty("Id")]
public long Id { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Address")]
public string Address { get; set; }
[JsonProperty("Country")]
public string Country { get; set; }
[JsonProperty("Phone")]
[JsonConverter(typeof(ParseStringConverter))]
public long Phone { get; set; }
}
string data="Your Json String"
var details = JsonConvert.DeserializeObject<Test>(data);
To make a list from your json values you can use a JObject, you don't have to know the objects stored in your Json in contrary to the others question.
JObject myObject = JsonConvert.DeserializeObject<JObject>(myJson);
List<object> myList = new List<object>();
foreach (var element in myObject)
{
myList.Add(element.Value);
}
If you already know what your json is made of, you can create a class that represent your object and implement the interface IEnumerable.
var myObject = JsonConvert.DeserializeObject<MyClass>(myJson);
var myArray = myObject2.ToArray():
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public int Phone { get; set; }
public object[] ToArray()
{
return new object[]
{
Id,
Name,
Address,
Country,
Phone
};
}
}
NB : the variable myJson in the previous codes is a string that represent your json as var myJson = "{\"Id\": 1000,\"Name\": \"May\",\"Address\": \"odyssey\",\"Country\": \"USA\",\"Phone\": \"12345\"}";

read multiple Json data from webservice

i have a web service that returns a Json string.
my problem is that i have difficulties to read it
i tried with:
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = reader.ReadToEnd();
var myobj = jsSerializer.Deserialize<List<CinfoRichiesta>>(jsonData);
but how can i get values from "students" and "locations"?
with javascript i used :" var j = jQuery.parseJSON(msg.d);" but i think with c# code would be different
this is an example of string:
{"Questions":{
"id":"2",
"BOOK":"3",
"students":{
"class":"3",
"theme","43"
},
"locations":{
"h":"0",
"L":"3"
}
}
}
First off, your JSON isn't valid so thats the first problem you have. You can verify this at http://jsonlint.com/ for example.
i have currently fixed this in the following way:
{
"Questions": {
"id": "2",
"BOOK": "3",
"students": {
"class": "3",
"theme": "na",
"43": "na"
},
"locations": {
"h": "0",
"L": "3"
}
}
}
Second your class should be correct, with the current JSON this should look something like this
public class Rootobject
{
public Questions Questions { get; set; }
}
public class Questions
{
public string id { get; set; }
public string BOOK { get; set; }
public Students students { get; set; }
public Locations locations { get; set; }
}
public class Students
{
public string _class { get; set; }
public string theme { get; set; }
public string _43 { get; set; }
}
public class Locations
{
public string h { get; set; }
public string L { get; set; }
}
After this you can deserialize it like this
var myobj = jsSerializer.Deserialize<List<Rootobject>>(jsonData);
And then you can get the information like this
myobj.Questions.students._class
You're deserializing to a collection of type CinfoRichiesta, which should hold a property value for students and locations.
Assuming that your JSON is correctly formatted and your class definition is suitable for the response (I recommend double checking it by pasting the entire response string into json2csharp.com)
Once that's all validated, you should be able to see the students and locations collections internally like so:
foreach(Question q in myobj)
{
Console.WriteLine(q.students.class)
}
which should give you the result of 3.
edit
I think your main question is why you're unable to access the properties of students and locations. Make sure Students is its own class as such:
public class Students
{
public int class { get; set; }
public int theme { get; set; }
}
and your locations class should be:
public class Locations
{
public int h { get; set; }
public int l { get; set; }
}
You should then have a questions class that instaniates both students and locations, as such:
public class Questions
{
public int id { get; set; }
public int book { get; set; }
public Student students { get; set; }
public Locations locations { get; set; }
}
When working with JSON deserialization, it's important that your object property names (ie class) match the response string in terms of case. So If you wrote it as public int Theme, it won't directly map.
Slightly annoying in terms of coding standards, but hey ho :-)

JSON Serializing confusion

I'm simply building a test Web API that takes a JSON payload and will simply send back the data in the array portion from my MVC Controller.
This is my current JSON string when serialized by my populated classes:
{"JobList":[{"ID":1,"Name":"Dave","Age":23,"StartDate":"10/23/2013 6:22:50 AM","JobTitle":"Developer"},{"ID":2,"Name":"John","Age":44,"StartDate":"10/23/2013 6:22:50 AM","JobTitle":"QA"},{"ID":3,"Name":"Dave","Age":23,"StartDate":"10/23/2013 6:22:50 AM","JobTitle":"Senior Developer"}]}
This is the object used to create this JSON:
var jobList = new JobsList()
{
JobList = new List<Jobs>()
{
new Jobs()
{
Age = 23,
ID = 1,
Name = "Dave",
StartDate = DateTime.Now.ToString(),
JobTitle = "Developer"
},
new Jobs()
{
Age = 44,
ID = 2,
Name = "John",
StartDate = DateTime.Now.ToString(),
JobTitle = "QA"
},
new Jobs()
{
Age = 23,
ID = 3,
Name = "Dave",
StartDate = DateTime.Now.ToString(),
JobTitle = "Senior Developer"
}
}
};
Here are my individual classes:
JobsList Class:
public class JobsList:IJobList
{
#region IJobList Members
public List<Jobs> JobList
{
get;
set;
}
#endregion
}
Jobs Class:
public class Jobs:Interfaces.IJobs
{
#region IJobs Members
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public string StartDate
{
get;
set;
}
public string JobTitle
{
get;
set;
}
#endregion
}
When I convert my JSON to produce classes through the use of JSON2Csharp the classes are produced as shown:
public class JobList
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string StartDate { get; set; }
public string JobTitle { get; set; }
}
public class RootObject
{
public List<JobList> JobList { get; set; }
}
This to me seems incorrect. Can anyone explain why I am not getting a 'Jobs' node in my JSON set to the JobsList array? And why do the generated JSON2CSharp classes map my 'Jobs' class as a JobList class?
Basically, it's because deserializer (in this case, JSON2CSharp) doesn't know what you named your original classes. Or how you structured them, for that matter. It doesn't know about any of that stuff you posted below "my current JSON string."
When you hand it that JSON object, that's all the information it is working with. So, it can tell that there's some sort of object (which it calls "RootObject"), which has an array of objects called "JobList". So it called the class "JobList". It had a choice there -- it could have simply called the list "JobList" and named the object something else... but it has no way of knowing that it was originally from an object named "Jobs", because that's not in the JSON. A different deserializer may have done it differently.
I am not familiar with JSON2CSharp specifically, so I don't know if it can do this, but there are frameworks that, given the object definition, can parse a JSON string with consistently named fields and load it into that object. For example, with Json.NET, you can do something like this:
JobsList jobList = JsonConvert.DeserializeObject<JobsList>(JsonString);

How to filter null or empty value from Json string

I have a one Model it's look like
public class DataClass
{
public string Name { get; set; }
public string Address { get; set; }
public string ContactNo { get; set; }
}
and I tried to convert in Json request using below mentioned code.
var l=new List<Data>();
l.Add(new Data(){Name="foo",Address ="bar",ContactNo =123});
l.Add(new Data(){Name="biz",Address ="baz"});
string json=JsonConvert.SerializeObject(l);
it will give me string like
[{"Name":"foo","Address":"bar","ContactNo":"123"},{"Name":"biz","Address":"baz","ContactNo":""}]
in output second ContactNo has a empty string but I don't need the field which has a no value or NULL .
can anyone please tell me what is the best way to avoid NULL or Empty field from Json request?
Thanks in Advance.
Change your model as below
public class Data
{
public string Name { get; set; }
public string Address { get; set; }
public int? ContactNo { get; set; }
}
and then serialize your object as below
var result = JsonConvert.SerializeObject(
l,
new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
});
I assume you are using Json.Net.
You can use the System.ComponentModel.DefaultValueAttribute. This allows you to mark a property to use a different default value than null.
So, if you want empty strings to be ignored in your JSON output you can update the model class to look like this:
public class DataClass
{
[DefaultValue("")]
public string Name { get; set; }
[DefaultValue("")]
public string Address { get; set; }
[DefaultValue("")]
public string ContactNo { get; set; }
}
Note that the SerializerSettings.DefaultValueHandling must be set to Ignore or IgnoreAndPopulate for this to be picked up.
A more thorough example of various approaches for reducing serialized json size is here:
http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size
1.You may add a flag in the model class.
public class DataClass{
public bool isIllegal{get;set;}
public string Name { get; set; }
public string Address { get; set; }
public string ContactNo { get; set{isIllegal=!string.isNullOrEmpty(value);)}
}
2.You can filter data whose isIllegal is false after JsonConvert.SerializeObject(l).

Json.NET Serializing my object gives me the wrong output

I'm having a bit of a problem with serializing my .NET objects into JSON using JSON.NET. The output I want to be serialized will have to look like this:
{"members":[
{"member":
{
"id":"4282",
"status":"1931",
"aktiv":"1",
"firmanavn":"firmname1",
"firmaUrl":"www.firmurl.dk",
"firmaUrlAlternativ":"",
"firmaSidstKontrolleretDato":"30-08-2010",
"firmaGodkendelsesDato":"07-03-2002"
}
},
{"member":
{
"id":"4283",
"status":"1931",
"aktiv":"1",
"firmanavn":"firmname2",
"firmaUrl":"www.firmurl.dk",
"firmaUrlAlternativ":"",
"firmaSidstKontrolleretDato":"30-08-2010",
"firmaGodkendelsesDato":"18-12-2000"
}
},
...... long list of members omitted
My .NET structure for now (still experimenting to get the right output) is like this:
public class Members
{
public List<Member> MemberList { get; set; }
}
and:
public class Member
{
[JsonProperty(PropertyName = "Id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Status")]
public string Status { get; set; }
[JsonProperty(PropertyName = "Aktiv")]
public string Aktiv { get; set; }
[JsonProperty(PropertyName = "Firmanavn")]
public string Firmanavn { get; set; }
[JsonProperty(PropertyName = "FirmaUrl")]
public string FirmaUrl { get; set; }
[JsonProperty(PropertyName = "AltFirmaUrl")]
public string AlternativFirmaUrl { get; set; }
[JsonProperty(PropertyName = "FirmaSidstKontrolleretDato")]
public string FirmaSidstKontrolleretDato { get; set; }
[JsonProperty(PropertyName = "FirmaGodkendelsesDato")]
public string FirmaGodkendelsesDato { get; set; }
}
What the above .NET structure gives me when calling:
string json = JsonConvert.SerializeObject(members, Newtonsoft.Json.Formatting.Indented);
Where 'members' is a list of members. Is this:
{
"Members": [
{
"Id": "1062",
"Status": "1933",
"Aktiv": "1",
"Firmanavn": "firmname",
"FirmaUrl": "http://www.firmurl.dk",
"AltFirmaUrl": "http://www.altfirmurl.dk",
"FirmaSidstKontrolleretDato": "13-09-2011",
"FirmaGodkendelsesDato": "13-09-2511"
},
{
"Id": "1060",
"Status": "1933",
"Aktiv": "1",
"Firmanavn": "firmname2",
"FirmaUrl": "http://www.firmurl.dk",
"AltFirmaUrl": "http://www.altfirmurldk",
"FirmaSidstKontrolleretDato": "13-09-2011",
"FirmaGodkendelsesDato": "13-09-2511"
},
So basically, the structure is right in that it creates the array of members as expected, but I am missing the "member": label on each of the member objects. Is there any way to make such a label? Some kind of class declaration, or something?
I hope my question is clear, if not - please let me know and I'll try to explain further.
Thanks a lot in advance.
/ Bo
It sounds like you just need to make an intermediary object with a property of that name to get the JSON you want; however, I'd consider using the JSON.net originally rendered JSON (as it is structurally better).

Categories