Dapper ORM multiple level nested object - c#

I'm trying to return SQL Server data using Dapper ORM that had nested object, so far here is what I'm doing
Model class
public class CustomerAll
{
public string KODELANG { get; set; }
public string GRUPLANG { get; set; }
public string NAMALANG { get; set; }
public string ALAMAT { get; set; }
public string STATUS { get; set; }
public List<NoDiscount> DISC_ACTIVE { get; set; }
}
public class NoDiscount
{
public string NO_DISC { get; set; }
public List<ProductDiscount> LIST_PRODUCT{ get; set; }
}
public class ProductDiscount
{
public string KODEPROD{ get; set; }
}
Raw query
SELECT CUSTOMER.KODELANG
,CUSTOMER.GRUPLANG
,CUSTOMER.NAMALANG
,CUSTOMER.ALAMAT
,CUSTOMER.STATUS
,DISCOUNT.NO_DISC
,PRODUCT.KODEPROD
FROM CUST_TABLE CUSTOMER, DCNT_TABLE DISCOUNT, PRODUCT_TABLE PRODUCT
WHERE CUSTOMER.KODELANG = DISCOUNT.KODELANG
AND DISCOUNT.NO_DISC = PRODUCT.NO_DISC
AND CUSTOMER.KODELANG = #CustNum
Controller class
var parameters = new { CustNum = customerNumber };
var lookup = new Dictionary<string, CustomerAll>();
con.Query<CustomerAll, NoDiscount, ProductDiscount, CustomerAll>(
querySql,
(c, n, p) =>
{
CustomerAll customer;
if (!lookup.TryGetValue(c.KODELANG, out customer))
{
lookup.Add(c.KODELANG, customer = c);
}
if (customer.DISC_ACTIVE == null)
{
customer.DISC_ACTIVE = new List<NoDiscount>();
}
if (p != null)
{
if (n.LIST_PRODUCT == null)
{
n.LIST_PRODUCT = new List<ProductDiscount>();
}
n.LIST_PRODUCT.Add(p);
}
customer.DISC_ACTIVE.Add(n);
return customer;
}
,parameters
,splitOn: "KODELANG, NO_DISC, KODEPROD");
return Ok(lookup.Values);
Here is what response returned
[
{
"KODELANG": "101308",
"GRUPLANG": "22",
"NAMALANG": "Name Example",
"ALAMAT": "Street number 4",
"STATUS": "A",
"DISC_ACTIVE": [
{
"NO_DISC": "DISC/1021/0001",
"LIST_PRODUCT": [
{
"KODEPROD": "TLBCA"
}
]
},
{
"NO_DISC": "DISC/1021/0001",
"LIST_PRODUCT": [
{
"KODEPROD": "TLBCB"
}
]
},
{
"NO_DISC": "DISC/3304/0009",
"LIST_PRODUCT": [
{
"KODEPROD": "ZVKAA"
}
]
}
]
}
]
What i'm trying to had is to be returned like these
[
{
"KODELANG": "101308",
"GRUPLANG": "22",
"NAMALANG": "Name Example",
"ALAMAT": "Street number 4",
"STATUS": "A",
"DISC_ACTIVE": [
{
"NO_DISC": "DISC/1021/0001",
"LIST_PRODUCT": [
{
"KODEPROD": "TLBCA"
},
{
"KODEPROD": "TLBCB"
},
{
"KODEPROD": "TLBCC"
}
]
},
{
"NO_DISC": "DISC/3304/0001",
"LIST_PRODUCT": [
{
"KODEPROD": "ZVKAA"
}
]
}
]
}
]
I don't want the LIST_PRODUCT getting added again if the NO_DISC are the same

Try this, beware that same NoDiscount object may have duplicate copys in diffierent customers.
var parameters = new { CustNum = customerNumber };
var customDict = new Dictionary<string, CustomerAll>();
con.Query<CustomerAll, NoDiscount, ProductDiscount, CustomerAll>(
querySql,
(c, n, p) =>
{
CustomerAll customer = null;
if (customDict.ContainsKey(c.KODELANG))
{
customer = customDict[c.KODELANG];
}
else
{
var customerObj = new CustomerAll()
{
KODELANG = c.KODELAN,
DISC_ACTIVE = new List<NoDiscount>()
};
customDict.Add(c.KODELANG, customerObj);
};
NoDiscount noDiscount = customer.DISC_ACTIVE.FirstOrDefault(x => x.NO_DISC == n.NO_DISC);
if (noDiscount ==null)
{
var noDiscountObj = new NoDiscount()
{
NO_DISC = n.NO_DISC,
LIST_PRODUCT = new List<ProductDiscount>()
};
noDiscount = noDiscountObj;
customer.DISC_ACTIVE.Add(noDiscountObj);
}
if (p != null && !noDiscount.LIST_PRODUCT.Contains(x=>x.KODEPROD==p.KODEPROD))
{
noDiscount.LIST_PRODUCT.Add(p);
}
return customer;
}
, parameters
, splitOn: "KODELANG, NO_DISC, KODEPROD");
return Ok(customDict.Values);

Related

Serialize JSON to JSON Array (Nested JSON) for POST Request 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"
}
]
}

Loop for add a json for each object in list

I'm making a tool that needs to export a json. He needs to be in this format:
{
"version" : "2",
"mangas" : [ {
"manga" : [ "sample", "manganame", 1234567890, 0, 0 ],
"chapters" : [ {
"u" : "urlexample",
"r" : 1
}, {
"u" : "urlexample",
"r" : 1
}, {
"u" : "urlexample",
"r" : 1
} ]
} ]
}
And this is my code:
void createJson(String manganame, String mangaoid, String sourceid)
{
String[] mangainfo = { "/manga/" + mangaoid, manganame, sourceid, "0", "0" };
var root = new RootObject()
{
version = "2",
mangas = new List<Manga>()
{
new Manga()
{
manga = mangainfo,
chapters = new List<Chapter>()
{
new Chapter
{
u = "sample",
r = 1
}
}
}
}
};
var json = JsonConvert.SerializeObject(root);
File.WriteAllText(#"D:\path.txt", json);
Console.WriteLine(json);
}
I'm lost, if someone can help me. Already give a search on Google, but the answer didn't come up in my head, already trying for a few time, slowly I'm getting but now is time to ask for help lol
For the list I was talking about, I'll explain it. I have a sqlite DB that have various information from mangas etc... I execute a query where I filter by a id, "SELECT * FROM MangaChapter WHERE manga_id = 'someid'", then i put the result on a list using a for loop. In the DB chapter url is stored like that "mr-chapter-166165" this is why i have had to concat string in chapterList.add.
List<String> chapterList = new List<String>();
cmd.CommandText = "SELECT * FROM MangaChapter WHERE manga_id = '3252'";
reader = cmd.ExecuteReader();
while (reader.Read())
{
chapterList.Add("/pagesv2?oid=" + reader.GetString("oid"));
}
For reference this is what I'm using to manage the sqlite db https://www.nuget.org/packages/dotConnect.Express.for.SQLite/
In the list, each chapter is something like that "/pagesv2?oid=mr-chapter-166165", if I print all the list on the console we'll be having something like that:
/pagesv2?oid=mr-chapter-166165
/pagesv2?oid=mr-chapter-166166
/pagesv2?oid=mr-chapter-166167
Here are the classes I generated from the given JSON sample
public class Chapter
{
[JsonProperty("u")]
public string U { get; set; }
[JsonProperty("r")]
public int R { get; set; }
}
public class Manga
{
[JsonProperty("manga")]
public IList<object> MangaInfos { get; set; }
[JsonProperty("chapters")]
public IList<Chapter> Chapters { get; set; }
}
public class Example
{
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("mangas")]
public IList<Manga> Mangas { get; set; }
}
and here the code to reproduce the give JSON sample
var d = new Example
{
Version = "2",
Mangas = new List<Manga>
{
new Manga()
{
MangaInfos = new List<object>{ "sample", "manganame", 1234567890, 0, 0 },
Chapters = new List<Chapter>
{
new Chapter()
{
U = "urlexample",
R = 1,
},
new Chapter()
{
U = "urlexample",
R = 1,
},
new Chapter()
{
U = "urlexample",
R = 1,
},
},
},
},
};
var json = JsonConvert.SerializeObject(d,Formatting.Indented);
Console.WriteLine(json);
The output looks like
{
"version": "2",
"mangas": [
{
"manga": [
"sample",
"manganame",
1234567890,
0,
0
],
"chapters": [
{
"u": "urlexample",
"r": 1
},
{
"u": "urlexample",
"r": 1
},
{
"u": "urlexample",
"r": 1
}
]
}
]
}
and live view at .net fiddle
Based on your comment, if you want to have various chapters for each "Manga", you have to change your data structure and that changes the Result Json you want.
maybe something like this?
public partial class Root
{
public long Version { get; set; }
public Mangas[] Mangas { get; set; }
}
public partial class Mangas
{
public Manga[] Manga { get; set; }
}
public partial class Chapter
{
public string U { get; set; }
public long R { get; set; }
}
public partial struct Manga
{
public long? Integer;
public string String;
public Chapter[] Chapters { get; set; }
}
Iterate through chapters. Solution below.
class Parent
{
public int Version { get; set; }
public List<Manga> mangas { get; set; }
}
class Manga
{
public List<object> manga { get; set; }
public List<Chapter> chapters { get; set; }
}
class Chapter
{
public string u { get; set; }
public int r { get; set; }
}
void createJson(String manganame, string mId, String mangaoid, long sourceid)
{
var json = new Parent()
{
Version = 2,
mangas = new List<Manga>()
{
new Manga()
{
manga = new List<object>{ "/manga/"+mangaoid, manganame, sourceid, 0, 0 },
chapters = Chapters(),
}
}
};
var sjson = JsonConvert.SerializeObject(json, Formatting.Indented);
File.WriteAllText(#"C:\Users\Izurii\Desktop\oi.json", sjson);
}
List<Chapter> Chapters()
{
List<Chapter> chapters = new List<Chapter>();
for(int i = 0; i < links.Count; i ++)
{
chapters.Add(
new Chapter()
{
u = links[i],
r = 1,
});
}
return chapters;
}

need help on desired JSON output

I have below class structures,
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Message
{
public int Size { get; set; } = 10;
public Student Student { get; set; }
}
Now I have list of messages like,
var messages = new List<Message>
{
new Message{ Size=10, Student=new Student{Id=1, Name="N1" } },
new Message{ Size=20, Student=new Student{Id=2, Name="N2" } }
};
which I want to write in JSON using Newtonsoft.Json,
using (var f = File.CreateText("C:\\Temp\\test.json"))
{
f.Write(JsonConvert.SerializeObject(messages));
}
This give below JSON output,
[
{
"Size": 10,
"Student": {
"Id": 1,
"Name": "N1"
}
},
{
"Size": 20,
"Student": {
"Id": 2,
"Name": "N2"
}
}
]
But I would like below output (without size and only one time root element student),
{
"Student": [
{
"Id": 1,
"Name": "N1"
},
{
"Id": 2,
"Name": "N2"
}
]
}
whats need to be done here? Thanks!
You need to refine your data to get desired result
first
var refindedResult = new { Students = messages.Select(m => m.Student) };
second pass it to json convertor
using (var f = File.CreateText("C:\\Temp\\test.json"))
{
f.Write(JsonConvert.SerializeObject(refindedResult ));
}
You can try to write a StudentModel class.
public class StudentModel
{
public IEnumerable<Student> Student { get; set; }
}
use linq get student collection from messages, then SerializeObject on it.
var res = new StudentModel()
{
Student = messages.Select(x => x.Student)
};
var json = JsonConvert.SerializeObject(res);
//f.Write(JsonConvert.SerializeObject(messages));
f.Write(JsonConvert.SerializeObject(messages.Select(m => m.Student)));
or, when you want a root object (Students, not Student)
f.Write(JsonConvert.SerializeObject(
new { Students = messages.Select(m => m.Student) } ));

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

Categories