Serialize JSON to JSON Array (Nested JSON) for POST Request C# - c#

This is what I'm trying to achieve. I'm trying to serialize my model into a JSON for post request to insert records
{
"Data": [
{
"employee_num": "7812345",
"code": "333",
"startdate": "2020-10-03"
},
{
"employee_num": "2345789",
"code": "444",
"startdate": "2020-10-03"
}
]
}
I'm stuck with this
{
"employee_num": "7812345",
"code": "333",
"startdate": "2020-10-03"
},
{
"employee_num": "2345789",
"code": "444",
"startdate": "2020-10-03"
}
Here is my code
var options = new JsonSerializerOptions
{
WriteIndented = false
};
var jsonString = JsonSerializer.Serialize(Model, options);
Newbie here

I used the Json Conerter from newtonsoft and got it the format you want.
Test t = new Test("Max", "Musterallee", "Mustermann#Muster.de");
Test t1 = new Test("Max2", "Musterallee2", "Mustermann2#Muster.de");
Test2 t2 = new Test2();
t2.addUser(t);
t2.addUser(t1);
var output = JsonConvert.SerializeObject(t2);
Console.WriteLine(output);
Test:
class Test
{
public string name { get; set; }
public string adress { get; set; }
public string email { get; set; }
public Test(string name, string adress, string email)
{
this.name = name;
this.adress = adress;
this.email = email;
}
}
Test2:
class Test2
{
public List<Test> Data;
public Test2()
{
Data = new List<Test>();
}
public void addUser (Test t1)
{
Data.Add(t1);
}
}
And the output looked like this:
{
"Data": [
{
"name": "Max",
"adress": "Musterallee",
"email": "Mustermann#Muster.de"
},
{
"name": "Max2",
"adress": "Musterallee2",
"email": "Mustermann2#Muster.de"
}
]
}

Well, Technically, your json suggests you should have a model like this:
public partial class SomeClass // You can choose some better class names.
{
[JsonProperty("Data")]
public List<Datum> Data { get; set; }
public SomeClass()
{
Data = new List<Datum>();
}
}
public partial class Datum
{
[JsonProperty("employee_num")]
public string EmployeeNum { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("startdate")]
public string Startdate { get; set; }
}
And this is how it is going to be populated:
var someClassObj = new SomeClass();
var datum = new Datum
{
EmployeeNum = "123",
Code = "321",
StartDate = "2003-03-03"
};
someClassObj.Data.Add(datum);
// You can add more objects in it as per your need.
And then to serialize this to a json you should do:
var json = JsonConvert.Serialize(someClassObj);
The output will be this:
{
"Data": [
{
"employee_num": "123",
"code": "321",
"startdate": "2003-03-03"
}
]
}

Related

How to deserialize dynamically named JSON in c#?

I know there is a lot of similar questions and i tried to use it for last 12 h but without result. So please give me any advice how to solved my problem.
My json response look like this:
{
"status": "OK",
"products": {
"dynamic10259668": {
"ean": "4525348924",
"sku": "9384573245",
"name": "name1",
},
"dynamic10630436": {
"ean": "983623203943",
"sku": "9312763245",
"name": "name2"
},
"dynamic10634396": {
"ean": "1002904820",
"sku": "9384763245",
"name": "name3"
},
"dynamic10634398": {
"ean": "3400901100",
"sku": "9312763245",
"name": "name4"
},
"dynamic10634399": {
"ean": "8100103701",
"sku": "454763245",
"name": "name5"
},
"dynamic10634766": {
"ean": "5600904820",
"sku": "9384763245",
"name": "name6"
}
}
}
And models:
public class ProductsList
{
public string status { get; set; }
public ListProducts products { get; set; }
}
public class ListProducts
{
public ListProduct product { get; set; }
}
public class ListProduct
{
public string ean { get; set; }
public string sku { get; set; }
public string name { get; set; }
}
Now i need e.g. Directory<"dynamic10259668", "9384573245"> but don't know how to access to product value. I have try this code:
ProductsList productsList = JsonConvert.DeserializeObject<ProductsList>(response.Content);
foreach (ListProduct singleProduct in productsList.products.product)
{
Console.WriteLine(singleProduct.name);
}
My most common error is:
System.NullReferenceException: Object reference not set to an instance of an object.
You need to use a Dictionary<string, ListProduct>. I believe that will do what you want.
I kept your ListProduct class, but modified ProductsList to look like this:
public class ProductsList
{
public string status { get; set; }
public Dictionary<string, ListProduct> products { get; set; }
}
When I do that, this code properly deserializes your JSON:
var result = JsonConvert.DeserializeObject<ProductsList>(theJson);
You can get to the data for dynamic10259668 using something like:
if (result.products.TryGetValue("dynamic10259668", out var item))
{
Debug.WriteLine($"Name: {item.name}, Ean: {item.ean}, Sku: {item.sku}");
}
It looks like you were hoping for a dictionary of product name to ean. If that is all you need then the following code would work:
dynamic d = JObject.Parse(response.Content);
var productDictionary = new Dictionary<string, string>();
foreach (var product in d.products)
{
productDictionary[product.Name] = (string)product.Value.ean;
}

Create json object with multiple array in c#

I want to create JSON object with following format:-
{
"result": [
{
"name": "John",
"address": "US",
},
{
"name": "Josh",
"address": "Japan",
}
],
"error": [
{
"message": "error-message"
}
],
"success": [
{
"message": "success-message"
}
]
}
I have tried the following, but it doesn't help me.
dynamic record = new { result = new {name="", address=""},
error = new {message=""},
success = new {message=""} };
Update 1:-
Here is my code:-
List addressList = new List();
// Loop over items within the container and URI.
foreach (var item in items)
{
dynamic record = new { result = new object[] {
new {name = item.name, address = item.address} } };
addressList.Add(record);
}
Result:-
[ {
"result": [
{
"name": "John",
"address": "US"
}
]
},
{
"result": [
{
"name": "Jack",
"address": "CA"
}
]
}
]
Expected json result:-
[{
"result": [{
"name": "John",
"address": "US"
}]
},
{
"result": [{
"name": "Jack",
"address": "CA"
}],
"error": [{
"message": "error-message"
}],
"success": [{
"message": "success-message"
}]
}
]
How do I update my code to get above expected json result?
You...create arrays. You're not doing that. You're creating individual objects.
Something along the lines of:
dynamic record = new {
result = new object[] {
new {name = "John", address = "US"},
new {name = "Josh", address = "Japan"}
},
error = new object[] /*...*/,
success = new object[] /*...*/
};
If you want exactly JSON, then newtonsoft.Json makes it easier:
Json json = new Json();
json.result = new object[] {
new {name = "John", address = "US"},
new {name = "Josh", address = "Japan"}
};
// json.error = ... and so on
string output = JsonConvert.SerializeObject(product);
The output you will have is:
{
"result": [
{
"name": "John",
"address": "US",
},
{
"name": "Josh",
"address": "Japan",
}
],
"error": [
{
...
}
]
}
To deserialize it back, use:
Json deserializedJson = JsonConvert.DeserializeObject<Json>(output);
you are not creating an array
if you want to create JSON arrays from c# you have to use the following POCO
public class Result
{
public string name { get; set; }
public string address { get; set; }
}
public class Error
{
public string message { get; set; }
}
public class Success
{
public string message { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
public List<Error> error { get; set; }
public List<Success> success { get; set; }
}
and then use Json.net
var json = JsonConvert.SerializeObject( "your instance of the root Object")
//You need to make this class structure first
public class Response
{
public List<Result> result { get; set; }
public List<Error> error { get; set; }
public List<Success> success { get; set; }
}
public class Result
{
public string name { get; set; }
public string address { get; set; }
}
public class Error
{
public string message { get; set; }
}
public class Success
{
public string message { get; set; }
}
// And then you can use it like this
var response = new Response()
{
result = new List<Result>
{
new Result() {name = "Jhon", address = "US"},
new Result() {name = "Jhon", address = "US"},
},
error = new List<Error>()
{
new Error() {message = "error-message 1"},
new Error() {message = "error-message 2"}
},
success = new List<Success>()
{
new Success(){message = "success-message 1"},
new Success(){message = "success-message 2"},
}
};
The Model Class
public class MegaMenu
{
public int department_id { get; set; }
public string department_name { get; set; }
public List<SectionListData> sectionListData { get; set; }
}
public class SectionListData
{
public int section_id { get; set; }
public string section_name { get; set; }
public List<ItemHeadList> itemHeadList { get; set; }
}
public class ItemHeadList
{
public int item_head_id { get; set; }
public string item_name { get; set; }
}
public class WrapperMegaMenu
{
public List<MegaMenu> megaMenuList { get; set; }
public string error { get; set; }
}
The Services
dept_result is the array of all department,section_result is the array of all section,Item_result is the array of all items
List<MegaMenu> listmenu = new List<MegaMenu>();
foreach (var each_dept in dept_result)
{
MegaMenu megaMenu = new MegaMenu();
megaMenu.department_id = each_dept.shopdepartment_id;
megaMenu.department_name = each_dept.name_en;
var temSectionList = section_result
.Where(item => item.shopdepartment_id == each_dept.shopdepartment_id).ToList().Select(sectionData => new SectionListData
{
section_id = sectionData.shopsection_id,
section_name = sectionData.name_en,
itemHeadList = Item_result.Where(itemHead => itemHead.shopsection_id == sectionData.shopsection_id).ToList().Select(itemHeadData => new ItemHeadList {
item_head_id = itemHeadData.item_head_id,
item_name = itemHeadData.name_en
}).ToList()
}).ToList();
megaMenu.sectionListData = temSectionList;
listmenu.Add(megaMenu);
}
//wrapperDept.departmentList = dept_result.ToList();
wrapper.megaMenuList = listmenu.ToList();
Result
{
"megaMenuList": [
{
"department_id": 71,
"department_name": "Baby's Hygiene",
"sectionListData": [
{
"section_id": 56,
"section_name": "Diapers",
"itemHeadList": []
},
{
"section_id": 57,
"section_name": "Wipes",
"itemHeadList": [
{
"item_head_id": 142,
"item_name": "Telivision"
}
]
}
]
}
]
}

How to convert JSON array into object list in the c#

I have a json object as below and I wants to convert it into
[
{
"Id": 1114,
"ParentId": 45333,
"IsActive": true,
"Name": "John",
"Contact": "123456"
},
{
"Id": 11344,
"ParentId": 54434,
"IsActive": false,
"Name": "Levi",
"Contact": "53552333"
},
{
"Id": 124433,
"ParentId": 535233,
"IsActive": false,
"Name": "Larry",
"Contact": "5443554"
}
]
}
I have tried below option but I am getting error "No parameterless constructor defined for type of 'MyApp.Emp[]'."
JavaScriptSerializer js = new JavaScriptSerializer();
Emp[] acc = js.Deserialize<Emp[]>(json);
Below is my Emp class
public class Emp
{
public Emp()
{
}
public int Id { get; set; }
public int ParentId { get; set; }
public bool IsActive { get; set; }
public string Name { get; set; }
public int Contact { get; set; }
}
Can anyone please show me how I can do it successfully.
Thanks
hopefully this answer is your want
PS : output
public JsonResult SaveResult()
{
return Json(new { err = "***"});
}
PS: input
public JsonResult ReadResult()
{
Object1 xxx = new Object1();
Object2 aa = new Object2();
xxx.x2.Add(aa);
aa = new Object2();
aa.y = "200";
aa.z = "222";
xxx.x2.Add(aa);
var json = JsonConvert.SerializeObject(xxx, Formatting.None);
return Json(json);
}
public class Object1
{
public string x1 = "aaaaa";
public IList<Object2> x2 = new List<Object2>();
}
public class Object2
{
public string y = "100";
public string z = "10";
}

How to deserialize JSON to my custom Class

Im new to JSON (and not sure if its the right way to do that), my problem is to deserialize my classes, all models implements this interface:
public interface IPersistent
{
object Id { get; set; }
}
Example of class:
public class ModelTest : IPersistent
{
private int? _id;
public object Id
{
get { return this._id; }
set { this._id = (int?)value; }
}
public string Name { get; set; }
}
Serialize method:
public void SerializeData<T>(T[] data)
{
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
DateFormatHandling = DateFormatHandling.IsoDateFormat
};
var result = JsonConvert.SerializeObject(data, Formatting.Indented, settings);
//more things happen, but not affect serialized data.
}
Deserialize method:
public T[] DeserializeData<T>(string objCached)
{
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
DateFormatHandling = DateFormatHandling.IsoDateFormat
}; //not sure if a need this settings, but...
T[] result = JsonConvert.DeserializeObject<T[]>(objCached, settings); //error here.
return result;
}
Error:
Message=Specified cast is not valid.
objCached data:
[
{
"$id": "1",
"Id": 1000,
"Name": "Name 1"
},
{
"$id": "2",
"Id": 2000,
"Name": "Name 2"
},
{
"$id": "3",
"Id": 3000,
"Name": "Name 3"
},
{
"$id": "4",
"Id": 4000,
"Name": "Name 4"
}
]
I tried validate JSON result using:
http://json2csharp.com/
Result:
public class RootObject
{
public string __invalid_name__$id { get; set; }
public int Id { get; set; }
public string Name { get; set; }
}
I'm looking for something that changes just the methods (Serialize and Deseriaize), can't change ALL my models (its a legacy without any unit test).
All you need to do is changing the set method of Id property. (Because value is long when read from json, which can not be casted toint?)
public class ModelTest : IPersistent
{
private int? _id;
public object Id
{
get { return this._id; }
set { this._id = new Nullable<int>((int)(long)value); }
}
public string Name { get; set; }
}

Newtonsoft JSON Deserialize AND jsonfreeze

I have a two simple PHP class
class Order{
public $orderNo;
public $lines = array();
public $paid = false;
public function addLine(OrderLine $line) {
$this->lines[] = $line;
}
public function setPaid($paid = true) {
$this->paid = true;
}
}
class OrderLine{
public function __construct($item, $amount){
$this->item = $item;
$this->amount = $amount;
}
public $item;
public $amount;
public $options;
}
Serialize object uses https://github.com/mindplay-dk/jsonfreeze
...
$json = new JsonSerializer;
$data = $json->serialize($order);
Have output:
{
"#type": "Order",
"orderNo": 123,
"lines": [{
"#type": "OrderLine",
"item": "milk \"fuzz\"",
"amount": 3,
"options": null
},{
"#type": "OrderLine",
"item": "cookies",
"amount": 7,
"options": {
"#type": "#hash",
"flavor": "chocolate",
"weight": "1\/2 lb"
}
}],
"paid": true
}
Send the string XMLRPC in VB.NET
As using Newtonsoft JSON get a live object?
As well as how to create a compatible format by analogy with the json string of living VB.net OR C# object?
Here's something you could start with. You create some classes with properties which represent the JSON Format (untested code, just as idea):
public class MyData
{
[JsonProperty("#type")]
public string Type { get; set; }
[JsonProperty("#orderNo")]
public int OrderNo { get; set;
[JsonProperty("paid")]
public bool Paid { get; set; }
[JsonProperty("lines")]
public List<MyDataLine> Lines { get; set; }
}
public class MyDataLines
{
[JsonProperty("#type")]
public string Type { get; set; }
[JsonProperty("options")]
public MyDataLinesOptions Options { get; set; }
// ... more
}
public class MyDataLinesOptions
{
// ... more
}
Then you can serialize and deserialize the the data like this:
string json = "the json data you received";
MyData myData = JsonConvert.DeserializeObject<MyData>(json);
// ...
json = JsonConvert.SerializeObject(myData);
"#type": "Order"
and
"#type": "OrderLine",
this is not a property, this is an indication of the type of the object

Categories