How to Create a new Json using array c# - c#

I need to create the following JSON:
[
{
"Name": [
{
"First Name": "Adam"
},
{
"Last Name": "Smith"
}
]
}
]
Please help as I have tried everything on here and on json.net
Thank you in advance.

Well... it is funny how things work once you know how its done :) and here for those who may have the same problem, this is the way to do it :
JObject myObject =
new JObject(
new JProperty("Name",
new JArray(
new JObject(
new JProperty("First Name", "Adam")),
new JObject(
new JProperty("Last Name", "Smith")))));
JArray myArray = new JArray
myArray.Add(myObject);

EDITED ANSWER: Removed old answer explaining what I thought the issue was with the JSON in the question. Changed to build C# objects that could create the JSON string above, haven't tried this but I think it should work:
Here are the C# classes:
public class Name
{
[JsonProperty(PropertyName = "First Name")]
public string FirstName { get; set; }
[JsonProperty(PropertyName = "Last Name")]
public string LastName { get; set; }
}
public class RootObject
{
[JsonProperty(PropertyName = "Name")]
public List<Name> Name { get; set; }
}
Create the name objects in the RootObject:
var myRootObj = new RootObject();
myRootObj.Name = new List<Name>();
var firstNameObj = new Name() { FirstName = "Adam" };
var secondNameObj = new Name() { LastName = "Smith" };
myRootObj.Name.Add(firstNameObject);
myRootObj.Name.Add(secondNameObject);
Now lets convert this object to JSON:
var json = JsonConvert.SerializeObject(myRootObj, Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
}););
I haven't tried this but I think it should create your JSON string, such as below:
{
"Name": [
{
"First Name": "Adam"
},
{
"Last Name": "Smith"
}
]
}

Related

Equivalent of JArray.FromObject() in .Net5?

We have a project which using System.Text.Json in .NET 5 instead of Newtonsoft JObject. Using Newtonsoft, it is pretty easy to replace dynamic JSON data e.g. as shown below:
siteDataObject["student"] = JArray.FromObject(studentservice.GetStudents());
When studentservice.GetStudents() is return List as below structure
internal class Student {
public int Id { get; set; }
public string Name { get; set; }
public string ContactPhone { get; set; }
public IEnumerable<MedicalRecord> MedicalRecords { get; set; }
}
internal class MedicalRecord {
public int Id { get; set; }
public string Name { get; set; }
public DateTime RecordDate { get; set; }
public IEnumerable<DiseaseLog> DiseaseLogs{ get; set; }
}
internal class DiseaseLog {
public int Id { get; set; }
public string Name { get; set; }
public DateTime LogDate { get; set; }
}
but in System.Text.Json
foreach (var element in doc.RootElement.EnumerateObject()) {
if (element.Name == "student") {
writer.WritePropertyName(element.Name);
}
else {
element.WriteTo(writer);
}
}
I don't know how to convert List<student> into JSON array data, when student class have many properties with multi collection inside.
Can anyone advise how to convert it ?
To clarify, I need to propose the full code for this, I have a dynamic json string and want to replace element : students into new record, the code will be
var dynamicJson = #"{'roomid':1,'roomcode':'Code001','students':[1],'contentdata':'say hello','footerdata':'cookie policy'}";
using MemoryStream stream = new MemoryStream();
using Utf8JsonWriter writer = new Utf8JsonWriter(stream);
using var dynamicDocument = JsonDocument.Parse(dynamicJson);
writer.WriteStartObject();
foreach (var element in dynamicDocument.RootElement.EnumerateObject())
{
if (element.Name == "students")
{
// unknown how to modify the student record into array
}
else
element.WriteTo(writer);
}
writer.WriteEndObject();
stream.Flush();
var modifyJson = Encoding.UTF8.GetString(stream.ToArray());
I know how to modify student value , if student element is string, but I don't know how to modify it into array, by using simple code. As student have multi class inside.
My expected result should be
{
"roomid": 1,
"roomcode": "Code001",
"students": [
{
"id": 1,
"Name": "Wilson",
"ContactPhone": "123-122-3311",
"MedicalRecords": [
{
"id": 101,
"Name ": "Medial record 101011",
"RecordDate": "2021-12-31",
"DiseaseLogs": [
{
"id": 18211,
"Name ": "Patient Log 19292",
"LogDate": "2020-1-31"
},
{
"id": 18212,
"Name ": "Patient Log 2911w",
"LogDate": "2020-3-31"
}
]
}
]
}
],
"contentdata": "say hello",
"footerdata": "cookie policy"
}
In .NET 5 there is no modifiable JSON Document Object Model built into to System.Text.Json. JsonDocument is read-only, and System.Text.Json.Nodes was only introduced in .NET 6. Thus, the easiest way to deserialize, modify and re-serialize free-form JSON in .NET 5 is to deserialize to some partial data model, with unknown values bound into a dictionary.
If you do not care about the order of properties at the root level, you could deserialize to a model with a public object students { get; set; } property, and bind the remaining elements to a JsonExtensionData overflow dictionary:
public class RootObject
{
public object students { get; set; }
[System.Text.Json.Serialization.JsonExtensionDataAttribute]
public IDictionary<string, object> ExtensionData { get; set; }
}
Then deserialize, modify and re-serialize as follows:
var students = new List<Student> { /* Initialize these as required... */ };
var dynamicJson = #"{""roomid"":1,""roomcode"":""Code001"",""students"":[1],""contentdata"":""say hello"",""footerdata"":""cookie policy""}";
var root = JsonSerializer.Deserialize<RootObject>(dynamicJson);
root.students = students;
var modifyJson = JsonSerializer.Serialize(root, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true });
Which results in
{
"students": [
{
"id": 1,
"name": "Wilson",
"contactPhone": "123-122-3311",
"medicalRecords": [
{
"id": 101,
"name": "Medial record 101011",
"recordDate": "2021-12-31T00:00:00",
"diseaseLogs": [
{
"id": 18211,
"name": "Patient Log 19292",
"logDate": "2020-01-31T00:00:00"
},
{
"id": 18212,
"name": "Patient Log 2911w",
"logDate": "2020-03-31T00:00:00"
}
]
}
]
}
],
"roomid": 1,
"roomcode": "Code001",
"contentdata": "say hello",
"footerdata": "cookie policy"
}
the students property must be declared as object because the input JSON already has an array containing a single integer value; declaring it as public List<Student> students { get; set; } would result in a deserialization when initially loading the JSON.
Demo fiddle #1 here.
If you do care about the order of properties at the root level, you could deserialize to an OrderedDictionary (an old order-preserving non-generic dictionary dating from .NET Framework 2.0 which is still around and supported), overwrite the "students" value, and re-serialize:
var students = new List<Student> { /* Initialize these as required... */ };
var dynamicJson = #"{""roomid"":1,""roomcode"":""Code001"",""students"":[1],""contentdata"":""say hello"",""footerdata"":""cookie policy""}";
var root = JsonSerializer.Deserialize<OrderedDictionary>(dynamicJson);
root["students"] = students;
var modifyJson = JsonSerializer.Serialize(root, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true });
Which results in
{
"roomid": 1,
"roomcode": "Code001",
"students": [
{
"id": 1,
"name": "Wilson",
"contactPhone": "123-122-3311",
"medicalRecords": [
{
"id": 101,
"name": "Medial record 101011",
"recordDate": "2021-12-31T00:00:00",
"diseaseLogs": [
{
"id": 18211,
"name": "Patient Log 19292",
"logDate": "2020-01-31T00:00:00"
},
{
"id": 18212,
"name": "Patient Log 2911w",
"logDate": "2020-03-31T00:00:00"
}
]
}
]
}
],
"contentdata": "say hello",
"footerdata": "cookie policy"
}
Demo fiddle #2 here.
In .NET 6 this all becomes easier through use of the System.Text.Json.Nodes editable JSON Document Object Model:
var dynamicJson = #"{""roomid"":1,""roomcode"":""Code001"",""students"":[1],""contentdata"":""say hello"",""footerdata"":""cookie policy""}";
var nodes = JsonSerializer.Deserialize<JsonObject>(dynamicJson);
nodes["students"] = JsonSerializer.SerializeToNode(students, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
var modifyJson = nodes.ToString();
But in .NET 5 this is not possible. Demo fiddle #3 here.
I think this is what you want (array or single nested object):
var student = new Student()
{
Name = "Student",
ContactPhone = "contact",
Id = 1,
MedicalRecords = new List<MedicalRecord>()
{
new MedicalRecord()
{
Name = "Medical Record 1",
RecordDate= DateTime.Now ,
Id = 1 ,
MedicalRecords = new List<DiseaseLog>()
{
new DiseaseLog(){ Name = "some disease" ,
LogDate = DateTime.Now, Id =1 }
}
}
}
};
var data = System.Text.Json.JsonSerializer.Serialize(student);
Console.WriteLine(data);
var list = new List<Student>();
list.Add(student);
var arrayData = System.Text.Json.JsonSerializer.Serialize(list);
Console.WriteLine(arrayData);

json.net list serialization to JSON Array

I'm using json.net to serialize an object to a json string. Now I have a list of Objects which I like to serialize into a Json array. However, I'm unable to do that with json.net and hope someone can point out my mistake.
I have the following classes:
class PeopleList {
public Person inputs { get; set; }
}
class Person {
public String name { get; set; }
public int age { get; set; }
}
I'm using the following code to serialize the objects:
var json = new List<PeopleList>();
Person p1 = new Person { name = "Name 1", age = 20 };
json.Add(new PeopleList { inputs = p1 });
Person p2 = new Person { name = "Name 2", age = 30 };
json.Add(new PeopleList { inputs = p2 });
string jsonString = JsonConvert.SerializeObject(json, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
This gives me the following output:
[
{
"inputs": {
"name": "Name 1",
"age": 20
}
},
{
"inputs": {
"name": "Name 2",
"age": 30
}
}
]
Here is what I actually want:
[
{
"inputs": [
{
"name": "Name 1",
"age": 20
}
]
},
{
"inputs": [
{
"name": "Name 2",
"age": 30
}
]
}
]
As you see I need every object in my list encapsulated with []. How can I achieve that with Json.net? Thanks!
If you want your inputs to be an array, you need to declare it as an array in your object :
class PeopleList {
public List<Person> inputs { get; set; }
}
Then you can use it :
var json = new List<PeopleList>();
List<Person> p1 = new List<Person> { new Person { name = "Name 1", age = 20 } };
json.Add(new PeopleList { inputs = p1 });
List<Person> p2 = new List<Person> { new Person { name = "Name 2", age = 30 } };
json.Add(new PeopleList { inputs = p2 });
string jsonString = JsonConvert.SerializeObject(json, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
based on your output and what you want you probably want to do something like this
Json2CSharpClass Converter
public class Person
{
public string name { get; set; }
public int age { get; set; }
}
public class PeopleList
{
public List<Person> inputs { get; set; }
}

Convert following class properties into Json format

I need to convert following Employee.cs class in json format,for that i wrote following code
//Employee.cs(In class file)
public class Employee
{
public string Name { get; set; }
public string Job { get; set; }
public string City { get; set; }
}
//In my MyPage.aspx page
Employee oEmployee1 =
new Employee { Name = "Pini", Job = "111", City = "30" };
Employee oEmployee2 =
new Employee { Name = "Yaniv", Job = "Developer", City = "Hyd" };
Employee oEmployee3 =
new Employee { Name = "Yoni", Job = "Developer", City = "Bglre" };
List<Employee> oList = new List<Employee>() { oEmployee1, oEmployee2, oEmployee3 };
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);
Response.Write("<pre>"+sJSON+"</pre>");
I got following output:
[{"Name":"Pini","Job":"111","City":"30"},{"Name":"Yaniv","Job":"Developer","City":"Hyd"},{"Name":"Yoni","Job":"Developer","City":"Bglre"}]
Is it any other way to convert to json format more effectively and i want to beautify json output
I would use JSON.NET Serializer with Formatting.Indented like below
string result= JsonConvert.SerializeObject(obj, Formatting.Indented);
Output
[
{
"Name": "Pini",
"Job": "111",
"City": "30"
},
{
"Name": "Yaniv",
"Job": "Developer",
"City": "Hyd"
},
{
"Name": "Yoni",
"Job": "Developer",
"City": "Bglre"
}
]
list<Employee> oEmployee=
{
new Employee() { Name = "Pini", Job = "111", City = "30" },
new Employee() { Name = "Pini", Job = "111", City = "30" },
new Employee() { Name = "Pini", Job = "111", City = "30" },
};
var oSerializer=new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);
Response.Write("<pre>"+sJSON+"</pre>");
add the System.Web.Script.Serialization reference
add refer this link
http://matijabozicevic.com/blog/csharp-net-development/csharp-serialize-object-to-json-format-using-javascriptserialization

Add array to a list of objects

this is the class to create my json object
public class RootObject
{
public string name { get; set; }
public string id { get; set; }
public string school { get; set; }
public List<object> details{ get; set; }
}
this is the way I'm creating a new object
var obj = new RootObject();
obj.name= "test";
obj.id = "null";
obj.school = "something else";
Then I am serializing the object using JavaScriptSerializer (this is working fine)
I need to add an array to this list of object "details" to get something like this:
{
"name ":"test",
"id":null,
"school ":"something else",
"details":["details1","detail2"]
}
I tried to add as string or element by element but without success. How can I solve this?
I strongly suggest you just use Json.NET:
obj.details = new List<object>
{
"details1", "details2"
};
Then, JsonConvert.SerializeObject(obj, Formatting.Indented) gives:
{
"name": "test",
"id": "null",
"school": "something else",
"details": [
"details1",
"details2"
]
}
You need to initialize the List:
obj.details = new List<object>();
Then to add data:
obj.details.Add("Details1");
obj.details.Add("Details2");

Add multiple items in JSON array to object in C# using Json.net

Can anyone tell me how I can deserialize an object that contains multiple attributes?
Given the scenario below, the code works fine.
public ActionResult Index()
{
string json = #"{""name"": ""Person 2"",""email"": ""example#example.com""}";
var emp = JsonConvert.DeserializeObject<Person>(json);
Response.Write(emp.name + emp.email);
return View();
}
public class Person
{
public string name { get; set; }
public string email { get; set; }
}
But what do I have to do if the array contains multiple items, e.g
string json = #"{""data"": [{""name"": ""Person 1"",""email"": ""test#test.com""},{""name"": ""Person 2"",""email"": ""example#example.com""}]}";
Thanks in advance
The answers already given below were perfect for the problem I asked, but now I've gone one step ahead. Can anyone advise on what I'd need to do if the json had an array in it e.g. the addition of an address in?
{
"data": [
{
"name": "Person 1",
"email": "test#test.com",
"address": {
"address1": "my address 1",
"address2": "my address 2"
}
},
{
"name": "Person 2",
"email": "example#example.com",
"address": {
"address1": "my address 1",
"address2": "my address 2"
}
}
]
}
Something like this has worked for me in the past:
JObject o = JObject.Parse(json); // This would be the string you defined above
// The next line should yield a List<> of Person objects...
List<Person> list = JsonConvert.DeserializeObject<List<Person>>(o["data"].ToString());
You might want to decorate your Person object as follows:
[JsonObject(MemberSerialization.OptIn)]
public class Person
{
[JsonProperty]
public string name{get;set;}
[JsonProperty]
public string email{get;set;}
}
You could use an anonymous type.
var template = new { data = new Person[] { } };
Person[] emps = JsonConvert
.DeserializeAnonymousType(json, template)
.data;
deserialize as :
public class JsonData
{
public List<Person> Data {get;set;}
}

Categories