Deserializing nested JSON Object and foreaching it throught - c#

What I'am attempt to do is deserialize json and foreach through that object and get Name, Lastname, Id values from it.
I think deserializing works but how can I foreach throught thoes values of that object and write out?
ResponseFromServer =
responseFromServer"{\"ReportName\":\"TestReport\",\"Results\":[
{
\"Name\":\"Test1\",
\"Lastname\":\"Test2\",
\"ID\":\"1111111111\",
},{
\"Name\":\"Test\",
\"Lastname\":\"Test\",
\"Id\":\"222222222\"
}
]}" string
Code so far:
object jsonObj = new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(responseFromServer);
var myObject = jsonObj.GetType().GetProperties();
foreach (var obj in myObject)
{
Console.WriteLine(obj);
}

I recommend, that you create a class for your JSON, like this:
public class Result
{
public string Name { get; set; }
public string Lastname { get; set; }
public string Id { get; set; }
}
public class ResponseClass
{
public string ReportName { get; set; }
public List<Result> Results { get; set; }
}
And with this class, you can convert your object and get the properties in a foreach, like the Lastname.
var yourObjectWithStructure = JsonConvert.DeserializeObject<ResponseClass>(responseFromServer,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
foreach (var result in objec.Results)
{
var id = result.Id;
var lastName = result.Lastname;
var name = result.Name;
}
Update:
You have "ID" and "Id" in your JSON response. I suggest, that "ID" should be "Id". Is that right?

I would use newtonsoft and create a concrete object with a List Property

If you download the NewtonSoft framework:
Then you can create a class for your response...
public class Report
{
public string ReportName {get; set;};
public string TestReport {get; set;};
public List<Person> Results {get; set;}
}
public class Person
{
public string Name {get; set};
public string LastName {get; set};
public int ID {get; set;}
}
and you can deserialise directly into a list of that object class like this:
using System.Web.Script.Serialization;
===============
List<Person> persons = JavaScriptSerializer().Deserialize<List<Report>>(responseFromServer);
Foreach(Person p in persons)
{
//stuff
}

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\"}";

Adding JArray to an existing property

I have this JSON:
{
"ID":123,
"Products":null,
"Title":"Products"
}
I want to add some data from DB to the "Products" node so my final json will look like so:
{
"ID":123,
"Products":[
{
"ID":1,
"Name":"AA"
},
{
"ID":2,
"Name":"BB"
}
],
"Title":"Products"
}
I'm using this code:
internal class Product
{
public int ID { get; set; }
public string Name { get; set; }
}
//simulate DB
var products= new List<Product>()
{
new Product() {ID=1,Name="AA" },
new Product() {ID=2,Name="BB" }
};
string JSONstr = FilesUtils.OpenFile(Path.Combine(Environment.CurrentDirectory, "Sample.json"));
JObject JSON = JObject.Parse(JSONstr);
((JValue)JSON["Products"]).Value = JObject.FromObject(products);
But I get an exception:
Object serialized to Array. JObject instance expected.
You can do:
JSON["Products"] = JToken.FromObject(products);
To add a new property, do the same thing, e.g.:
JSON["TimeStamp"] = JToken.FromObject(DateTime.UtcNow);
Notes:
The item setter for JObject will add or replace the property with the specified name "Products".
JToken.FromObject() serializes any .Net object to a LINQ to JSON hierarchy. JToken is the abstract base class of this hierarchy and so can represent both arrays, objects, and primitives. See here for details.
Sample fiddle.
The expected object will have to be (according to your JSON). If that's the JSON you want you might consider wrapping it up and adding the ID and a Title as shown in the JSON.
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
}
public class YourObject
{
public int ID { get; set; }
public List<Product> Products { get; set; }
public string Title { get; set; }
}

deserialize json object does not work

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);

JSON model binding with variable keys .net mvc4

What is a useful model which could bind a json object with arbitrary keys? Assume your json could look like:
{"##hello": "address","#world": "address1","name": "address"}
or
{"##hello": "address","#world": "address1","firstname": "foo", "lastname":"bar"}
or
{"##hello": "address","#world": "address1","children": [{"name":"foo"},{"name":"bar"}]}
So that means you only know at run time how the json model looks like. My current state is, that it seems the best practice is to send the json object as string to the controller and deserialize the json string it to an object.
public ActionResult mappingNodes(string model) {
dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(model);
}
public class Children
{
[JsonProperty("name")]
public string Name { get; set; }
}
public class YourClass
{
[JsonProperty("##hello")]
public string Hello { get; set; }
[JsonProperty("#world")]
public string World { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("firstname")]
public string FirstName { get; set; }
[JsonProperty("lastname")]
public string LastName { get; set; }
[JsonProperty("children")]
public Children[] Children { get; set; }
}
var json1 = "{ '##hello': 'address','#world': 'address1','name': 'address'}";
var json2 = "{ '##hello': 'address','#world': 'address1','name': 'address', 'firstname': 'foo', 'lastname':'bar'}";
var json3 = "{ '##hello': 'address','#world': 'address1','name': 'address','children': [{'name':'foo'},{'name':'bar'}]}";
var model1 = JsonConvert.DeserializeObject<YourClass>(json1);
var model2 = JsonConvert.DeserializeObject<YourClass>(json2);
var model3 = JsonConvert.DeserializeObject<YourClass>(json3);

C# object partially convert to JSON(MVC)

I have the following code in a controller.
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
public ActionResult JsonObject()
{
Person[] persons = new Person[]{
new Person{Name="John", Age=26, Birthday=new DateTime(1986,1,1)},
new Person{Name="Tom", Age=10, Birthday=new DateTime(2002, 1, 9)}
};
return Json(persons, JsonRequestBehavior.AllowGet);
}
Normally, I got the result like this:
[{"Name":"John","Age":26,"Birthday":"/Date(504892800000)/"},{"Name":"Tom","Age":10,"Birthday":"/Date(1010505600000)/"}]
That's okay, however, I want to make an option for the user: not to display birthday. So, the expecting result would be like this:
[{"Name":"John","Age":26},{"Name":"Tom","Age":10}]
How can I not to serialize the Birthday property to JSON?
You have two options:
1) Add a [ScriptIgnore] attribute to the Person class:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
[ScriptIgnore]
public DateTime Birthday { get; set; }
}
2) Return an anonymous type that contains only the properties you want:
var toReturn = persons.Select(x => new {x.Name, x.Age});
return Json(toReturn, JsonRequestBehavior.AllowGet);
EDIT: I wasn't aware that the desired columns had to be dynamically chosen. You can use the following because objects and dictionaries are the same thing in Javascript.
First, create an extension that creates a dictionary of your desired properties:
public static class JSONExtensions
{
public static IDictionary<string, object> ToJsonObject(this object instance, string[] includedProperties)
{
var jsonObject = new Dictionary<string, object>();
foreach (var property in instance.GetType().GetProperties())
{
if (includedProperties.Any(x=> x.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
{
jsonObject[property.Name] = property.GetValue(instance);
}
}
return jsonObject;
}
}
Next, use this extension method before serializing:
var toReturn = persons.Select(x => x.ToJsonObject(desiredColumnss));
return Json(toReturn, JsonRequestBehavior.AllowGet);
just define a new class as DTO, which contains only required fields.
public class PersonDTO
{
public string Name { get; set; }
public int Age { get; set; }
}
After that, you can PersonDTO

Categories