I want to deserialize my json object to my student class
var result = JsonConvert.DeserializeObject<Student>(data);
My json data
{
"student":{
"fname":"997544",
"lname":"997544",
"subject":"IT",
"grade":"F"
}
}
My student class
[Serializable]
public class Student
{
[JsonProperty("fname")]
public string FirstName{ get; set; }
[JsonProperty("lname")]
public string LastName{ get; set; }
[JsonProperty("subject")]
public string Subject { get; set; }
[JsonProperty("grade")]
public string Grade { get; set; }
}
The code does not work, the error says:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type
because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Your JSON string currently represents an object with an inner object property named Student. If you want to deserialize to your Student object your JSON string should look like this:
{
"fname":"997544",
"lname":"997544",
"subject":"IT",
"grade":"F"
}
If it's not easy to change your JSON you could also use JObject to help you like so:
var jobject = JObject.Parse(jsonData);
var student = JsonConvert.DeserializeObject<Student>(jobject["student"].ToString());
Or as others have pointed out you can simply create another class wrapper and deserialize directly to that.
if you have to use your downloaded json then you need to create another model
class for it
[Serializable]
public class Student
{
[JsonProperty("fname")]
public string FirstName{ get; set; }
[JsonProperty("lname")]
public string LastName{ get; set; }
[JsonProperty("subject")]
public string Subject { get; set; }
[JsonProperty("grade")]
public string Grade { get; set; }
}
[Serializable]
public class NewModel
{
public Student Student { get; set; }
}
then deserialize
var result = JsonConvert.DeserializeObject<NewModel>(data);
You JSON object is inside a nameless Root / Parent Object.
So Use something like the following.
var result = JsonConvert.DeserializeObject<RootObject>(data);
then your Student instance can be access as result.student
Ex:
string firstName = result.student.FirstName;
I use Json2CSharp to generate the additional RootObject class.
Here's all the class definitions
[Serializable]
public class Student
{
[JsonProperty("fname")]
public string FirstName{ get; set; }
[JsonProperty("lname")]
public string LastName{ get; set; }
[JsonProperty("subject")]
public string Subject { get; set; }
[JsonProperty("grade")]
public string Grade { get; set; }
}
[Serializable]
public class RootObject
{
public Student student { get; set; }
}
Because you're trying to deal with the object from JSON, it's easiest to start with
var jStudent = JObject.Parse(jsonData);
You can then go to any sub property of the JObject through key reference and deserialize as you're expecting.
var student = JsonConvert.DeserializeObject<Student>(jStudent["student"].ToString());
Hope that helps
Since you cannot change your Json string, you need to modify your class structure to match it. Note that the student object is wrapped in another class. The class structure to use this Json data looks like this:
public class Wrapper
{
public Student Student { get; set; }
}
public class Student
{
[JsonProperty("fname")]
public string FirstName { get; set; }
[JsonProperty("lname")]
public string LastName { get; set; }
[JsonProperty("subject")]
public string Subject { get; set; }
[JsonProperty("grade")]
public string Grade { get; set; }
}
And deserialise like this:
var wrapper = JsonConvert.DeserializeObject<Wrapper>(data);
Related
{"id":"190155258007","name":"name","email":"mail#gmail.com","gender":"male",
"friends":{"data":[{"id":"1331173146","name":"friendname1"},{"id":"120497111959","name":"friendname2"},{"id":"9980211103","name":"friendname3"},
{"id":"77872075894","name":"friendname4"}]}
I am getting this JSON result but I can get deserialized value from single values but this friends array returns a null value in C#. How to fix this?
Use Newtonsoft.Json
Create your custom class:
public class MyResponse {
public string id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string gender { get; set; }
public friend friends { get; set; }
public class friend{
public List<data> data {get;set;}
public class data {
string id {get;set;}
string name {get;set;}
}
}
}
Now you can deserialize your json like:
MyResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject<MyResponse>("You json string here");
Now this response object will be filled by your return json string. If you don't have Newtonsoft.Json dll, you can download it from the following link:
https://www.nuget.org/packages/newtonsoft.json/
if you dont want to use custom class, you can use dynamic keyword like:
dynamic stuff = JsonConvert.DeserializeObject("Your json string here");
string name = stuff.name;
string email= stuff.email;
And so on.
How can we parse if json fields contains a colon(:)? Like this:
{
"dc:creator":"Jordan, Micheal",
"element:publicationName":"Applied Ergonomics",
"element:issn":"2839749823"
}
In fact I wonder how to do this with a library like restsharp, for mapping?
Using Json.Net
string json = #"{
""dc:creator"":""Jordan, Micheal"",
""element:publicationName"":""Applied Ergonomics"",
""element:issn"":""2839749823""
}";
var pub = JsonConvert.DeserializeObject<Publication>(json);
public class Publication
{
[JsonProperty("dc:creator")]
public string creator { set; get; }
[JsonProperty("element:publicationName")]
public string publicationName { set; get; }
[JsonProperty("element:issn")]
public string issn { set; get; }
}
OR
Console.WriteLine(JObject.Parse(json)["dc:creator"]);
If you use DataContractJsonSerializer, DataMemberAttribute has property Name which can be used to override default name. This means that when you deserialize json value of property dc:creator is assigned to Publication::Creator property and on the contrary when you serialize C# object.
For example:
public class Publication
{
[DataMember(Name="dc:creator")]
public string Creator { set; get; }
[DataMember(Name="element:publicationName")]
public string PublicationName { set; get; }
[DataMember(Name="element:issn")]
public string Issn { set; get; }
}
If you choose to use Json.Net, #L.B's answer is the way to go.
I am getting JSON that is being returned from a REST web service for survey responses. It has arrays for the name portion of some of the name value pairs. Additionally the names will be variable depending on the type of questions asked. I'm using JSON.net and trying to deserialize the returned value into some type of object tree that I can walk but can't figure out what structure to use to have it filled in.
I tested the following snippet in LinqPad and fields is always empty. Is there someway to easily read in the variable data or do I have to parse it in code?
void Main() {
string json = #"{
'result_ok':true,
'total_count':'51',
'data':[{
'id':'1',
'status':'Deleted',
'datesubmitted':'2015-01-12 10:43:47',
'[question(3)]':'Red',
'[question(4)]':'Blue',
'[question(18)]':12,
'[variable(\'STANDARD_IP\')]':'127.0.0.1',
'[variable(\'STANDARD_GEOCOUNTRY\')]':'United States'
}]
}";
var responses = JsonConvert.DeserializeObject<RootObject>(json);
responses.Dump();
}
public class RootObject {
public bool result_ok { get; set; }
public string total_count { get; set; }
public List<Response> data { get; set; }
}
public class Response {
public string id { get; set; }
public string status { get; set; }
public string datesubmitted { get; set; }
public List<object> fields = new List<object>();
}
Change the fields property in your Response class to be a Dictionary<string, object>, then mark it with a [JsonExtensionData] attribute like this:
public class Response
{
public string id { get; set; }
public string status { get; set; }
public string datesubmitted { get; set; }
[JsonExtensionData]
public Dictionary<string, object> fields { get; set; }
}
All of the fields with the strange property names will then be placed into the dictionary where you can access them as normal. No extra code is required.
Here is a demo: https://dotnetfiddle.net/1rQUXT
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).
I want to create a multidimensional json object based on a c# class. I normally do it like this:
public class foo
{
public string name { get; set; }
public int age { get; set; }
}
And serialize a new instance of the class with a JavaScriptSerializer. But lets say that i want to add another json array containing the persons friends inside the main json array. Example array: Accessing data in a multidimensional JSON array with jQuery
Hope you get the idea. Thanks
If I get your question corect, something like this should work...
public class Person
{
public string name { get; set; }
public int age { get; set; }
public List<Person> Friends { get; set; }
}
How are you creating the JSON version of your class, foo?
JavaScriptSerializer and Controller.JSON (in MVC) support serializing IEnumerable derived types, so you could have the class:
public class foo
{
public string name { get; set; }
public int age { get; set; }
public List<Bar> friends {get; set;}
}
and your JSON serialized class would include the list of Bar objects.