Coming here after learning about C# classes Constructors and ArrayLists so that not to put a completely dumb question here :)
I'm trying to Deserialize below Nested Lists of JSON returned from an API GET call as below:
I've been able to get the value from the empArra (Field: Emp), but subsequent lists like yearArray, prod and sale are not returning there values.
Can you please look into the below code that where is it doing wrong?
JSON
[
{
"employee":"156718100",
"availability":[
{
"year":2018,
"sales":{
"availability":"Maybe",
"reason":""
},
"prod":{
"availability":"Maybe",
"reason":""
}
},
{
"year":2019,
"sales":{
"availability":"Maybe",
"reason":""
},
"prod":{
"availability":"Maybe",
"reason":""
}
},
{
"year":2020,
"sales":{
"availability":"Maybe",
"reason":""
},
"top":{
"availability":"Maybe",
"reason":""
}
},
{
"year":2021,
"sales":{
"availability":"Maybe",
"reason":""
},
"prod":{
"availability":"Maybe",
"reason":""
}
}
]
}
]
Classes
public class sale
{
public string SaleAvailability { get; set; }
public string SaleReason { get; set; }
public sale(string pSaleAvailability, string pSaleReason)
{
this.SaleAvailability = pSaleAvailability;
this.SaleReason = pSaleReason;
}
public override string ToString()
{
return string.Format("{0} {1}", SaleAvailability, SaleReason);
}
}
public class prod
{
public string ProdAvailability { get; set; }
public string ProdReason { get; set; }
public prod(string pProdAvailability, string pProdReason)
{
this.ProdAvailability = pProdAvailability;
this.ProdReason = pProdReason;
}
public override string ToString()
{
return string.Format("{0} {1}", ProdAvailability, ProdReason);
}
}
public class yearArray
{
public int Year { get; set; }
public yearArray(int pYear)
{
this.Year = pYear;
}
List<sale> Sale { get; set; } = new List<sale>();
List<prod> Prod { get; set; } = new List<prod>();
}
public class rootAvailability
{
public List<yearArray> YearArray { get; set; } = new List<yearArray>();
}
public class empArray
{
public string Emp { get; set; }
public List<rootAvailability> RootAvailability { get; set; } = new List<rootAvailability>();
}
public class rootArray
{
public List<empArray> EmpArrays { get; set; } = new List<empArray>();
}
main() method
(After getting the response from API)
IRestResponse response = client.Execute<rootArray>(request);
//Console.WriteLine(response.Content);
List<rootArray> rootArrays = JsonConvert.DeserializeObject<List<rootArray>>(response.Content);
List<empArray> empArrays = JsonConvert.DeserializeObject<List<empArray>>(response.Content);
List<rootAvailability> rootAvailabilities = JsonConvert.DeserializeObject<List<rootAvailability>>(response.Content);
List<yearArray> yearArrays = JsonConvert.DeserializeObject<List<yearArray>>(response.Content);
List<sale> clsSale = JsonConvert.DeserializeObject<List<sale>>(response.Content);
List<prod> clsProd = JsonConvert.DeserializeObject<List<prod>>(response.Content);
foreach (var rootitem in rootArrays)
{
foreach (var emparrayitem in empArrays)
{
Console.WriteLine("NSN: " + emparrayitem.Emp);
foreach (var rootavailabbilitiesitem in rootAvailabilities)
{
foreach (var yearArrayItem in yearArrays)
{
Console.WriteLine("Year: " + yearArrayItem.Year);
foreach (var saleItem in clsSale)
{
Console.WriteLine("SaleAvailability: " + saleItem.SaleAvailability);
Console.WriteLine("SaleReason: " + saleItem.SaleReason);
}
foreach (var prodItem in clsProd)
{
Console.WriteLine("SaleAvailability: " + prodItem.ProdAvailability);
Console.WriteLine("SaleReason: " + prodItem.ProdReason);
}
}
}
}
}
Results
Emp: 159252663
Year: 0
SaleAvailability:
SaleReason:
SaleAvailability:
SaleReason:
You have two problems with your approach:
You want to deserialize the same source over and over again (response.Content) for different class instances. It can be deserialized into one object type: your top level entity.
Your data model does not reflect your data. For example YearArray should have a single Prod and Sale property not a list of them.
You have several options how to fix it. Let me share with you the two most common ones:
With proper naming
Your object model should look like this:
public class Sale
{
public string Availability { get; set; }
public string Reason { get; set; }
}
public class Prod
{
public string Availability { get; set; }
public string Reason { get; set; }
}
public class MidLevel
{
public int Year { get; set; }
public Sale Sales { get; set; }
public Prod Top { get; set; }
}
public class TopLevel
{
public string Employee { get; set; }
public List<MidLevel> Availability { get; set; } = new List<MidLevel>();
}
Then all you need to do is to call the following command:
var result = JsonConvert.DeserializeObject<TopLevel[]>(json);
Now, your result will be populated with all the data.
With JsonProperty
If you don't want to use the same names in your domain model which is used in the json then you can define the mapping between these two worlds via JsonProperty attributes.
Now your domain model can look like this:
public class SalesInformation
{
[JsonProperty(PropertyName = "availability")]
public string Avail { get; set; }
[JsonProperty(PropertyName = "reason")]
public string Reasoning { get; set; }
}
public class ProdInformation
{
[JsonProperty(PropertyName = "availability")]
public string Availability { get; set; }
[JsonProperty(PropertyName = "reason")]
public string Reasoning { get; set; }
}
public class MidLevel
{
[JsonProperty(PropertyName = "year")]
public int AvailYear { get; set; }
[JsonProperty(PropertyName = "sales")]
public SalesInformation SalesInfos { get; set; }
[JsonProperty(PropertyName = "top")]
public ProdInformation ProdInfos { get; set; }
}
public class TopLevel
{
[JsonProperty(PropertyName = "employee")]
public string Emp { get; set; }
[JsonProperty(PropertyName = "availability")]
public List<MidLevel> Availabilities { get; set; } = new List<MidLevel>();
}
The usage would be exactly the same:
var result = JsonConvert.DeserializeObject<TopLevel[]>(json);
UPDATE: How to display data
To represent hierarchy in a console application can be achieved in may ways. Here I will use indentation. I've introduced the following tiny helper method:
public static void WriteWithIndent(int level, string message) => Console.WriteLine("".PadLeft(level * 2) + message);
With this in hand the data visualization could be achieved in the following way:
var result = JsonConvert.DeserializeObject<TopLevel[]>(json);
foreach (var topLevel in result)
{
Console.WriteLine($"Employee: {topLevel.Emp}");
foreach (var midLevel in topLevel.Availabilities)
{
WriteWithIndent(1, $"Year: {midLevel.AvailYear}");
WriteWithIndent(1, "Sales:");
WriteWithIndent(2, $"Avail: {midLevel.SalesInfos.Avail}");
WriteWithIndent(2, $"Reason: {midLevel.SalesInfos.Reasoning}");
WriteWithIndent(1, "Top:");
WriteWithIndent(2, $"Avail: {midLevel.ProdInfos.Avail}");
WriteWithIndent(2, $"Reason: {midLevel.ProdInfos.Reasoning}");
}
}
The printed output will look like this:
Employee: 156718100
Year: 2018
Sales:
Avail: Maybe
Reason:
Top:
Avail: Maybe
Reason:
Year: 2019
Sales:
Avail: Maybe
Reason:
Top:
Avail: Maybe
Reason:
Year: 2020
Sales:
Avail: Maybe
Reason:
Top:
Avail: Maybe
Reason:
Year: 2021
Sales:
Avail: Maybe
Reason:
Top:
Avail: Maybe
Reason:
Related
I have an object which has a property which is list. Based on that list I want to filter property of it along with other properties of an object.
I have following object
{
Adult: 1,
Child: 0,
Infant: 0,
Origin: 'ABC',
Destination: 'XYZ',
DomesticFlightInfos: [{
FlightID: flightId1,
FareID: fareId1,
IsInbound: true
},
{
FlightID: flightId2,
FareID: fareId2,
IsInbound: false
}
]
};
I want following two objects
{
Adult: 1,
Child: 0,
Infant: 0,
Origin: 'ABC',
Destination: 'XYZ',
DomesticFlightInfos: [{
FlightID: flightId1,
FareID: fareId1,
IsInbound: true
}]
};
Adult: 1,
Child: 0,
Infant: 0,
Origin: 'ABC',
Destination: 'XYZ',
DomesticFlightInfos: [{
FlightID: flightId2,
FareID: fareId2,
IsInbound: false
}]
I was trying to do reservation.DomesticFlightInfos.Where(x => !x.IsInbound); which was wrong and got casting issue. What could be the best solution for it?
C# Object
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
new DomesticFlightReservation()
{
Adult = 1,
Child = 0,
Infant = 0,
Origin = "ABC",
Destination = "XYZ",
DomesticFlightInfos = new List<DomesticFlightInfo>(){
new DomesticFlightInfo{
FlightID= "flightId1",
FareID= "fareId1",
IsInbound= true
},
new DomesticFlightInfo {
FlightID= "flightId2",
FareID= "fareId2",
IsInbound= false
}
}
};
}
}
public class DomesticFlightReservation
{
public int Adult { get; set; } = 0;
public int Child { get; set; } = 0;
public int Infant { get; set; } = 0;
public string Origin { get; set; }
public string Destination { get; set; }
public List<DomesticFlightInfo> DomesticFlightInfos { get; set; }
}
public class DomesticFlightInfo
{
public string FlightID { get; set; }
public string FareID { get; set; }
// True for inbound, false for outbound
public bool IsInbound { get; set; }
}
Since you haven't provided C# object, assuming your C# objects to be defined as
public class DomesticFlightInfo
{
public string FlightID { get; set; }
public string FareID { get; set; }
public bool IsInbound { get; set; }
}
public class RootObject
{
public int Adult { get; set; }
public int Child { get; set; }
public int Infant { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
public List<DomesticFlightInfo> DomesticFlightInfos { get; set; }
}
If your intention is to separate the Inbounds and Outbound flights to separate groups, you could
var reservation = JsonConvert.DeserializeObject<RootObject>(str);
var flattenedReservation = new[]{reservation}.SelectMany(x=>x.DomesticFlightInfos
.GroupBy(v=>v.IsInbound)
.Select(c =>
{
x.DomesticFlightInfos = c.ToList();
return x;
}));
var jsonCollection = flattenedReservation.Select(x=> JsonConvert.SerializeObject(x,settings));
If your intention is to separate out each flight info into separate jsons, you could
var flattenedReservation = new[]{reservation}.SelectMany(x=>x.DomesticFlightInfos
.Select(c =>
{
x.DomesticFlightInfos = new List<DomesticFlightInfo>{c};
return x;
}));
var jsonCollection = flattenedReservation.Select(x=> JsonConvert.SerializeObject(x));
Output
If you have a list as a collection, you can use SelectMany
So, if you have a list
List<RootObject> rootObjects
then you can do this like flatten the list to get individual items:
rootObjects.SelectMany(x=> x.DomesticFlightInfos).Where(y => !y.IsInbound);
I am trying to get a field from the response from the rest services in the Web API we are building. The JSON looks like this:
{
"d": {
"results": [{
"__metadata": {
"id": "Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)",
"uri": "https://teams.ax.org/sites/js/project/_api/Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)",
"etag": "\"6\"",
"type": "SP.Data.St_x0020_CdsListItem"
},
"Folder": {
"__deferred": {
"uri": "https://teams.ax.org/sites/js/project/_api/Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)/Folder"
}
},
"ParentList": {
"__deferred": {
"uri": "https://teams.ax.org/sites/js/project/_api/Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)/ParentList"
}
},
"PM_x0020_NameId": 220,
"St_x0020_Name": "<div class=\"ExternalClassA14DB0FF86994403B827D91158CF34B0\">KO</div>",
}]
}}
I created these model classes:
public class SharepointDTO
{
public class Metadata
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("uri")]
public string uri { get; set; }
[JsonProperty("etag")]
public string etag { get; set; }
[JsonProperty("type")]
public string type { get; set; }
}
public class Deferred
{
[JsonProperty("uri")]
public string uri { get; set; }
}
public class Folder
{
[JsonProperty("__deferred")]
public Deferred __deferred { get; set; }
}
public class ParentList
{
[JsonProperty("__deferred")]
public Deferred __deferred { get; set; }
}
public class Result
{
[JsonProperty("__metadata")]
public Metadata __metadata { get; set; }
[JsonProperty("Folder")]
public Folder Folder { get; set; }
[JsonProperty("ParentList")]
public ParentList ParentList { get; set; }
[JsonProperty("PM_x0020_NameId")]
public int PM_x0020_NameId { get; set; }
[JsonProperty("St_x0020_Name")]
public string St_x0020_Name { get; set; }
}
public class D
{
[JsonProperty("results")]
public IList<Result> results { get; set; }
}
public class RootObject
{
[JsonProperty("d")]
public D d { get; set; }
}
}
No trying to call the rest service from the Web API and need to get the St_x0020_Name from response and store in a string.
SharepointDTO.RootObject retSharepointobj = await GetfromSharepoint(StNumber);
string StName = retSharepointobj.d.results.St_x0020_Name.ToString();
I am deserializing the JSON in the GetfromSharepoint method like
using (var client_sharePoint = new HttpClient(handler))
{
var response = client_sharePoint.GetAsync(SP_URL).Result;
var responsedata = await response.Content.ReadAsStringAsync();
var returnObj = JsonConvert.DeserializeObject<SharepointDTO.RootObject>(responsedata);
return returnObj;
}
But it throws an error:
'System.Collections.Generic.IList' does not contain a definition for 'St_x0020_Name' and no extension method 'St_x0020_Name' accepting a first argument of type 'System.Collections.Generic.IList' could be found (are you missing a using directive or an assembly reference?)
results is an array, so you have either loop thru like
foreach(var item in retSharepointobj.d.results){
string StName = item.St_x0020_Name.ToString();
}
or get a specific element, for example a first element like:
SharepointDTO.RootObject retSharepointobj = await GetfromSharepoint(StNumber);
string StName = retSharepointobj.d.results[0].St_x0020_Name.ToString();
or you can add an extra check like that
SharepointDTO.RootObject retSharepointobj = await GetfromSharepoint(StNumber);
if(retSharepointobj.d.results.length > 0){
string StName = retSharepointobj.d.results[0].St_x0020_Name.ToString();
}
Shouldn't this line:
string StName = retSharepointobj.d.results.St_x0020_Name.ToString();
Be like this?
string StName = retSharepointobj.d.results.First().St_x0020_Name.ToString();
I am trying to build a function where a user can upload a json file.
Each row in the json file can have a different nr of properties(i.e. columns).
5 of these properties are always the same so I want those to be deserialized to an object. The rest of the properties have to go into a dictionary or something.
Here is a json example:
[{
"Projekt": "Bakker Bouw Service",
"Ruimte": "Hoofdgebouw",
"Apparaat": {
"project": "Bosboom001",
"versie": "812"
},
"Apparaat naam": "",
"Status": "Goedgekeurd",
"Testname1": "",
"Testname3": "2000-01-04T10:37:00+01:00",
"Testname7": "2001-01-03T00:00:00+01:00"
}, {
"Projekt": "Bakker Bouw Service",
"Ruimte": "Hoofdgebouw",
"Apparaat": {
"project": "Vlaams003",
"versie": "713"
},
"Apparaat naam": "",
"Status": "Goedgekeurd",
"Testname1": "Slecht",
"Testname7": "2000-01-04T10:37:00+01:00",
"Testname9": "2001-01-03T00:00:00+01:00",
"Testname16": "18MOhm",
"Testname23": "OK"
}, {
"Projekt": "Bakker Bouw Service",
"Ruimte": "Hoofdgebouw",
"Apparaat": {
"project": "Vlaams017",
"versie": "73"
},
"Apparaat naam": "GDR34Z5",
"Status": "Afgekeurd",
"Testname7": "2000-01-04T10:37:00+01:00",
"Testname10": "0,012mA",
"Testname16": "200MOhm",
"Testname23": "200MOhm",
"Testname25": "Afgekeurd",
"Testname31": "0,01mA"
}
]
Here is the class to deserialze to:
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
public Dictionary<string, object> testNames { get; set; }
}
public class Apparaat
{
public string project { get; set; }
public string versie { get; set; }
}
And here is the controller
public IActionResult Upload(IFormFile file)
{
string fileContent = null;
using (var reader = new StreamReader(file.OpenReadStream()))
{
fileContent = reader.ReadToEnd();
}
List<KeuringRegel> keuringRegelList = JsonConvert.DeserializeObject<List<KeuringRegel>>(fileContent);
//More stuff here
}
The json successfully deserializes but the testNames value is always null. I understand why, because there is no testNames property in the Json file. However, how do I achieve what I want? I am no Json expert.
One way you can do this, assuming that there is only testNameNNNN entries as supplemental values, is to use the JsonExtensionDataAttribute like this:
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
[JsonExtensionData()]
public Dictionary<string, object> testNames { get; set; }
}
This will give you the values whos don't fall into one of the other properties:
It's a bit of a "blunt instrument" but you could always perform some post-processing on the returned instances of KeuringRegel to remove any errant entries from testNames (i.e. things that don't match the pattern testNameNNNN).
If your JSON does contain things that don't match the pattern testNameNNNN which would therefore get included, you could implement a custom class for the testNames property:
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
[JsonExtensionData()]
public TestNames testNames { get; set; }
}
public class TestNames : Dictionary<string, object>
{
public new void Add(string key, object value)
{
if (key.StartsWith("testname", StringComparison.OrdinalIgnoreCase))
{
base.Add(key, value);
}
}
}
This will check each item that is added to the testNames dictionary and prevent its addition if (as in my comment where I had an item in the JSON of "badgerBadgetCatCat": 3) it doesn't match the pattern.
Here u are full example
internal class Program
{
private static void Main(string[] args)
{
var str = #"[{
""Projekt"": ""Bakker Bouw Service"",
""Ruimte"": ""Hoofdgebouw"",
""Apparaat"": {
""project"": ""Bosboom001"",
""versie"": ""812""
},
""Apparaat naam"": """",
""Status"": ""Goedgekeurd"",
""Testname1"": """",
""Testname3"": ""2000-01-04T10:37:00+01:00"",
""Testname7"": ""2001-01-03T00:00:00+01:00""
}, {
""Projekt"": ""Bakker Bouw Service"",
""Ruimte"": ""Hoofdgebouw"",
""Apparaat"": {
""project"": ""Vlaams003"",
""versie"": ""713""
},
""Apparaat naam"": """",
""Status"": ""Goedgekeurd"",
""Testname1"": ""Slecht"",
""Testname7"": ""2000-01-04T10:37:00+01:00"",
""Testname9"": ""2001-01-03T00:00:00+01:00"",
""Testname16"": ""18MOhm"",
""Testname23"": ""OK""
}, {
""Projekt"": ""Bakker Bouw Service"",
""Ruimte"": ""Hoofdgebouw"",
""Apparaat"": {
""project"": ""Vlaams017"",
""versie"": ""73""
},
""Apparaat naam"": ""GDR34Z5"",
""Status"": ""Afgekeurd"",
""Testname7"": ""2000-01-04T10:37:00+01:00"",
""Testname10"": ""0,012mA"",
""Testname16"": ""200MOhm"",
""Testname23"": ""200MOhm"",
""Testname25"": ""Afgekeurd"",
""Testname31"": ""0,01mA""
}
]";
var sw = Stopwatch.StartNew();
var result = Mapper.Map(str);
sw.Stop();
Console.WriteLine($"Deserialized at {sw.ElapsedMilliseconds} ms ({sw.ElapsedTicks} tiks)");
}
public static class Mapper
{
static Mapper()
{
List<string> names = new List<string>();
IEnumerable<PropertyInfo> p = typeof(KeuringRegel).GetProperties().Where(c => c.CanRead && c.CanWrite);
foreach (var propertyInfo in p)
{
var attr = propertyInfo.GetCustomAttribute<JsonPropertyAttribute>();
names.Add(attr != null ? attr.PropertyName : propertyInfo.Name);
}
Properties = names.ToArray();
}
private static string[] Properties { get; }
public static KeuringRegel[] Map(string str)
{
var keuringRegels = JsonConvert.DeserializeObject<KeuringRegel[]>(str);
var objs = JsonConvert.DeserializeObject(str) as IEnumerable;
var objectList = new List<JObject>();
foreach (JObject obj in objs)
objectList.Add(obj);
for (var i = 0; i < keuringRegels.Length; i++)
{
keuringRegels[i].testNames = new Dictionary<string, object>();
foreach (var p in objectList[i].Children().OfType<JProperty>().Where(c => !Properties.Contains(c.Name)).ToArray())
keuringRegels[i].testNames.Add(p.Name, p.Value);
}
return keuringRegels;
}
}
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
public Dictionary<string, object> testNames { get; set; }
}
public class Apparaat
{
public string project { get; set; }
public string versie { get; set; }
}
}
This class I created myself:
public class member
{
public string account_name { get; set; }
public long account_id { get; set; }
public Rootobject[] rootobject { get; set; }
}
This are the classes VS created for me autmatically using an example JSON answer:
public class Rootobject
{
public string status { get; set; }
public Meta meta { get; set; }
public Data data { get; set; }
}
public class Meta
{
public int count { get; set; }
}
public class Data
{
public _507888780[] _507888780 { get; set; }
}
public class _507888780
{
public All all { get; set; }
public int tank_id { get; set; }
}
public class All
{
public int spotted { get; set; }
public int hits_percents { get; set; }
public int wins { get; set; }
...
}
A small part of the JSON response from the API server I use looks like this:
{
"status": "ok",
"meta": {
"count": 1
},
"data": {
"507888780": [
{
"all": {
"spotted": 467,
"hits_percents": 83,
"wins": 281,
},
"tank_id": 2849
},
{
"all": {
"spotted": 224,
"hits_percents": 63,
"wins": 32,
},
"tank_id": 9473
},
}
}
This is the code I use to read out the tanks a member has (including all the stats) where Request(string) is just the http request.
private List<member> memberlist = new List<member>(100);
private void DoStuff()
{
memberlist = JsonConvert.DeserializeObject<List<member>>(result_member);
foreach (var member in memberlist)
{
string result_tank = Request("https://api.worldoftanks.eu/wot/tanks/stats/?application_id=" + application_id + "&account_id=" + member.account_id + "&tank_id=" + tanks + "&fields=all.battles%2C+all.wins%2C+all.damage_dealt%2C+all.frags%2C+all.hits_percents%2C+all.piercings%2C+all.shots%2C+all.spotted%2C+all.survived_battles%2C+all.tanking_factor");
var Rootobject = JsonConvert.DeserializeObject<Rootobject>(result_tank);
foreach (var tank in _507888780)
{
richTextBox1.Text += Rootobject.data._507888780[tank].tank_id + Rootobject.data._507888780[tank].all.spotted.ToString() + "...";
}
}
}
Now, I want to be able to search up all the different tanks including their stats for all members. Right now I'm getting the error in the line I want to print "Type Tank_Statistics._507888780 cannot be implicitly converted to int." Earlier on I alos got an error with a missing IEnumerable which I dont have right now though..
Anyways .. I can't make it work somehow.. it would be very kind if someone would be able to help me on this ;)
Seems that you should replace this
richTextBox1.Text += Rootobject.data._507888780[tank].tank_id + Rootobject.data._507888780[tank].all.spotted.ToString() + "...";
to this
richTextBox1.Text += tank.tank_id + tank.all.spotted.ToString() + "...";
--------KEY----------------------------VALUE-----
newrowstart ------------------------newrowstart
LearnerTelephones_ID----------------3797d9ab-df28-423e-b847-f7c1abbac26a
LearnerTelephones_IsFirst-----------FALSE
newrowstart ------------------------newrowstart
LearnerTelephones_L_ID ------------88a86894-f3fa-4ff0-bb0c-814a2434e841
newrowstart ------------------------newrowstart
LearnerTelephones_Ln_IDNAME---------my name
LearnerTelephones_Ln_IDAdd --------my id address
newrowend ------------------------newrowend
newrowstart-------------------------newrowstart
LearnerTelephones_Ln_IDNAME---------my name2
LearnerTelephones_Ln_IDAdd----------my id address2
newrowend ------------------------newrowend
newrowend --------newrowend
LearnerTelephones_Notes --------null
LearnerTelephones_TelephoneNumber---1234 505050
LearnerTelephones_UseForText--------null
newrowend---------------------------newrowend
My datatable is as above, and it has breaking rows- startrow and endrow.
I want to create insert statement out of this datatable,
For ex.
insert into table1(LearnerTelephones_ID,LearnerTelephones_IsFirst,LearnerTelephones_L_ID , LearnerTelephones_Ln_IDNAME,
LearnerTelephones_Ln_IDAdd,LearnerTelephones_Notes,LearnerTelephones_TelephoneNumber,LearnerTelephones_UseForText)
values(,,,,,,..)
so total 4 insert statements i need to create.
You should first write some classes which are useful to deserialize your json string.
class LearnerTelephones
{
public string ID { get; set; }
public bool IsFirstPointOfContact { get; set; }
public LocationType LocationType { get; set; }
public string Notes { get; set; }
public string TelephoneNumber { get; set; }
public bool UseForTextMessages { get; set; }
}
class LocationType
{
public string ID { get; set; }
public IList<NameType> NameType { get; set; }
}
class NameType
{
public string IDNAME { get; set; }
public string IDAdd { get; set; }
}
class RootObject
{
public LearnerTelephones LearnerTelephones { get; set; }
}
Then install newton.json package into your project, if not installed.
newton.json package link
Then you can easily parse and deserialize json string into your c# objects
and iterate as per your requirement, and can create insert statement.
class Program
{
static void Main(string[] args)
{
string json = "{\"LearnerTelephones\":{ \"ID\": \"eaf32af9-07bf-4d87-8aeb-84ac8860dee9\", \"IsFirstPointOfContact\": true, \"LocationType\": { \"ID\": \"ebbbaa62-f1f0-4010-8b0b-ee744eafc1de\", \"NameType\":[{ \"IDNAME\": \"my name\", \"IDAdd\": \"my id address\" }, { \"IDNAME\": \"my name2\", \"IDAdd\": \"my id address2\" } ] }, \"Notes\": null, \"TelephoneNumber\": \"028 3282 3717\", \"UseForTextMessages\": true } }";
RootObject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(json);
string sql = string.Empty;
if (obj != null)
{
for (int i = 0; i < obj.LearnerTelephones.LocationType.NameType.Count; i++)
{
var obj1 = obj.LearnerTelephones;
sql += string.Format("insert into table1(LearnerTelephones_ID,LearnerTelephones_IsFirst,LearnerTelephones_L_ID , LearnerTelephones_Ln_IDNAME, LearnerTelephones_Ln_IDAdd,LearnerTelephones_Notes,LearnerTelephones_TelephoneNumber,LearnerTelephones_UseForText) values " +
"('{0}','{1}','{2}','{3}','{4}','{5}','{6}');", obj1.ID, obj1.IsFirstPointOfContact, obj1.LocationType.NameType[i].IDNAME, obj1.LocationType.NameType[i].IDAdd, obj1.Notes, obj1.TelephoneNumber, obj1.UseForTextMessages);
}
}
Console.WriteLine(sql);
Console.Read();
}
}
I guess this will useful it. and update logic as per your requirement.