Getting JSON in this format after serializing the data from the data table
This is the result after reading the excel file and storing the data in a data table. Later serialized using newtosoft.json into below JSON output
JSON getting now below:
[{ "Id": "1", "Profit": "33.332999999999998", "Telephone": "123", "Email": "user1#testmail.com" }, { "Id": "1", "Profit": "21.21", "Telephone": "43", "Email": "user11#testmail.com" }, { "Id": "2", "Profit": "49.000999999999998", "Telephone": "22", "Email": "user2#testmail.com" }, { "Id": "2", "Profit": "10.1", "Telephone": "876", "Email": "user22#testmail.com" }]
Expected format
[{ "Id": "1", "Profits": ["33.332999999999998", "21.21"], "Telephones": ["43", "123"], "Emails": ["user1#testmail.com", "user11#testmail.com"] }, { "Id": "2", "Profits": ["49.000999999999998", "10.1"], "Telephones": ["876", "22"], "Emails": ["user2#testmail.com", "user22#testmail.com"] }]
Can anyone please help with this?
try this
var json=...origin json
var jD = JsonConvert.DeserializeObject<DataOrigin[]>(json);
jD=jD.OrderBy(d => d.Id).ToArray();
var prevId=string.Empty;
var list=new List<Data>();
foreach (var item in jD)
{
if(item.Id!=prevId)
{
prevId=item.Id;
list.Add(new Data(Convert.ToInt32(item.Id), item.Profit, item.Telephone, item.Email));
}
else
{
var prevIdInt=Convert.ToInt32(prevId);
var prevItem=list.Last(l =>l.Id==prevIdInt );
prevItem.MergeItem(item.Profit,item.Telephone,item.Email);
}
}
var result = JsonConvert.SerializeObject(list);
result
[
{
"Id": 1,
"Profits": [
33.333,
21.21
],
"Telephones": [
"123",
"43"
],
"Emails": [
"user1#testmail.com",
"user11#testmail.com"
]
},
{
"Id": 2,
"Profits": [
49.001,
10.1
],
"Telephones": [
"22",
"876"
],
"Emails": [
"user2#testmail.com",
"user22#testmail.com"
]
}
]
classes
public class DataOrigin
{
public string Id { get; set; }
public double Profit { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
}
public class Data
{
public int Id { get; set; }
public List<double> Profits { get; set; }
public List<string> Telephones { get; set; }
public List<string> Emails { get; set; }
public Data(int id,double profit,string phone, string email)
{
Id=id;
Profits = new List<double>(){profit};
Telephones = new List<string>(){phone};
Emails = new List<string>(){email};
}
public void MergeItem (double profit,string phone, string email)
{
Profits.Add(profit);
Telephones.Add(phone);
Emails.Add(email);
}
}
Here is the solution:
var data = [{
"Id": "1",
"Profit": "33.332999999999998",
"Telephone": "123",
"Email": "user1#testmail.com"
}, {
"Id": "1",
"Profit": "21.21",
"Telephone": "43",
"Email": "user11#testmail.com"
}, {
"Id": "2",
"Profit": "49.000999999999998",
"Telephone": "22",
"Email": "user2#testmail.com"
}, {
"Id": "2",
"Profit": "10.1",
"Telephone": "876",
"Email": "user22#testmail.com"
}]
var temp = {};
data.forEach(x => {
if (temp[x.Id] == undefined) {
temp[x.Id] = {}
temp[x.Id]['Id'] = x.Id
temp[x.Id]['Profit'] = []
temp[x.Id]['Telephone'] = []
temp[x.Id]['Email'] = []
}
temp[x.Id].Profit.push(x.Profit)
temp[x.Id].Telephone.push(x.Telephone)
temp[x.Id].Email.push(x.Email)
})
var finalResponse = []
for (const [key, value] of Object.entries(temp)) {
finalResponse.push(value)
}
Related
Given 2 JSON strings:
[
{
"id":"BA",
"description":"BrandA",
"values":[
{
"id":"CategoryA",
"description":"CategoryA"
},
{
"id":"CategoryB",
"description":"CategoryB"
},
{
"id":"CategoryC",
"description":"CategoryC"
},
{
"id":"CategoryD",
"description":"CategoryD"
},
{
"id":"CategoryE",
"description":"CategoryE"
},
{
"id":"CategoryF",
"description":"CategoryF"
},
{
"id":"CategoryG",
"description":"CategoryG"
},
{
"id":"CategoryH",
"description":"CategoryH"
}
]
},
{
"id":"BB",
"description":"BrandB",
"values":[
{
"id":"CategoryA",
"description":"CategoryA"
},
{
"id":"CategoryB",
"description":"CategoryB"
},
{
"id":"CategoryC",
"description":"CategoryC"
}
]
}
]
AND
[
{
"id":"BA",
"description":"BrandA",
"values":[
{
"id":"CategoryA",
"description":"CategoryA"
},
{
"id":"CategoryC",
"description":"CategoryC"
}
]
},
{
"id":"BB",
"description":"BrandB",
"values":[
{
"id":"CategoryB",
"description":"CategoryB"
}
]
}
]
First one is the original. The second are the values that I want to remove from the original. So basically, if there is a match on brand and category between first and second JSON, regardless of the order of the elements, I want that match to be removed.
The expected result would be someting like this:
[
{
"id":"BA",
"description":"BrandA",
"values":[
{
"id":"CategoryB",
"description":"CategoryB"
},
{
"id":"CategoryD",
"description":"CategoryD"
},
{
"id":"CategoryE",
"description":"CategoryE"
},
{
"id":"CategoryF",
"description":"CategoryF"
},
{
"id":"CategoryG",
"description":"CategoryG"
},
{
"id":"CategoryH",
"description":"CategoryH"
}
]
},
{
"id":"BB",
"description":"BrandB",
"values":[
{
"id":"CategoryA",
"description":"CategoryA"
},
{
"id":"CategoryC",
"description":"CategoryC"
}
]
}
]
Catagory A and C in Brand A were removed as well as Category B in Brand B.
Based in some research, I was using https://github.com/wbish/jsondiffpatch.net, tried to work with it's functions, but so far I didn't manage to achieve the result I want. Also, to solve this by processing JSON direcly is not a must. If there is a simpler solution to achieve that by converting them to lists and use something like LINQ for example, it works for me as well (tried that, but didn't manage to find a way to do this comparison).
Thanks in advance.
If performance does not matter, the JsonSerializer and LINQ can be used:
Model
public class JsonModel
{
public class ValueModel
{
public string Id { get; set; }
public string Description { get; set; }
}
public string Id { get; set; }
public string Description { get; set; }
public IEnumerable<ValueModel> Values { get; set; }
}
Deserialize and LINQ
string json1Str = #"[...]";
string json2Str = #"[...]";
var opt = new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var json1 = System.Text.Json.JsonSerializer.Deserialize<List<JsonModel>>(json1Str, opt);
var json2 = System.Text.Json.JsonSerializer.Deserialize<List<JsonModel>>(json2Str, opt);
var result = json1.
Join(json2, j1 => j1.Id, j2 => j2.Id, (j1, j2) => new JsonModel
{
Id = j1.Id,
Description = j1.Description,
Values = j1.Values.Where(j1 => !j2.Values.Select(val => val.Id).Contains(j1.Id))
});
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(result, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
}
Result
[
{
"Id": "BA",
"Description": "BrandA",
"Values": [
{
"Id": "CategoryB",
"Description": "CategoryB"
},
{
"Id": "CategoryD",
"Description": "CategoryD"
},
{
"Id": "CategoryE",
"Description": "CategoryE"
},
{
"Id": "CategoryF",
"Description": "CategoryF"
},
{
"Id": "CategoryG",
"Description": "CategoryG"
},
{
"Id": "CategoryH",
"Description": "CategoryH"
}
]
},
{
"Id": "BB",
"Description": "BrandB",
"Values": [
{
"Id": "CategoryA",
"Description": "CategoryA"
},
{
"Id": "CategoryC",
"Description": "CategoryC"
}
]
}
]
I'm trying to deserialize a json in c# with Newtonsoft, but when i try to print the elements, it returns null.
The json is the following:
{
"data": [
{
"ufs": [
{
"delivery": [
{
"grade": "100",
"name": "P01",
"id": 10,
"status": "submitted"
},
{
"name": "P02",
"id": 11,
"status": "new"
}
],
"name": "UF1",
"id": "18"
},
{
"delivery": [
{
"name": "P03",
"id": 12,
"status": "new"
},
{
"name": "P04",
"id": 13,
"status": "new"
}
],
"name": "UF2",
"id": "19"
}
],
"name": "M1",
"id": "5"
},
{
"ufs": [
{
"delivery": [
{
"name": "P01",
"id": 6,
"status": "submitted"
},
{
"name": "P02",
"id": 7,
"status": "new"
}
],
"name": "UF1",
"id": "23"
},
{
"delivery": [
{
"name": "P03",
"id": 8,
"status": "new"
},
{
"name": "P04",
"id": 9,
"status": "new"
}
],
"name": "UF2",
"id": "24"
}
],
"name": "M2",
"id": "6"
}
]
}
So, having this JSON, i went to this site to generate the classes i would need, that are the following ones:
public class Delivery
{
public string grade { get; set; }
public string name { get; set; }
public int id { get; set; }
public string status { get; set; }
}
public class Uf
{
public List<Delivery> delivery { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class Root
{
public List<Uf> ufs { get; set; }
public string name { get; set; }
public string id { get; set; }
}
So finally, when i deserialize the JSON with this line
List<Root> myDeserializedClass = JsonConvert.DeserializeObject<List<Root>>(json);
And try to print
foreach (Root item in myDeserializedClass)
{
Console.WriteLine(item.ufs.Count);
}
It says "Root.ufs.get returned null."
Any clue of where im mistaking? Thanks for the help!
Grettings from Spain!
You class structure would be like this
public class Delivery
{
public string grade { get; set; }
public string name { get; set; }
public int id { get; set; }
public string status { get; set; }
}
public class Uf
{
public List<Delivery> delivery { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class Data
{
public List<Uf> ufs { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class Root
{
public List<Data> data { get; set; }
}
When you needed to deserialize the Json you will do like this
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(json);
Here is the json that I used
string json = #"{'data': [
{
'ufs': [
{
'delivery': [
{
'grade': '100',
'name': 'P01',
'id': 10,
'status': 'submitted'
},
{
'name': 'P02',
'id': 11,
'status': 'new'
}
],
'name': 'UF1',
'id': '18'
},
{
'delivery': [
{
'name': 'P03',
'id': 12,
'status': 'new'
},
{
'name': 'P04',
'id': 13,
'status': 'new'
}
],
'name': 'UF2',
'id': '19'
}
],
'name': 'M1',
'id': '5'
},
{
'ufs': [
{
'delivery': [
{
'name': 'P01',
'id': 6,
'status': 'submitted'
},
{
'name': 'P02',
'id': 7,
'status': 'new'
}
],
'name': 'UF1',
'id': '23'
},
{
'delivery': [
{
'name': 'P03',
'id': 8,
'status': 'new'
},
{
'name': 'P04',
'id': 9,
'status': 'new'
}
],
'name': 'UF2',
'id': '24'
}
],
'name': 'M2',
'id': '6'
}
]
}";
How to combine JSON objects in the same response that has the same key and value. like if I've two objects that have the same language: Python I want to combine them and List the remaining data under this language Python I don't want it being repeated
[
[
{
"language": "Python",
"id": 319029846,
"full_Name": "beurtschipper/Depix",
"name": "Depix"
},
{
"language": "Python",
"id": 319169382,
"full_Name": "benwilber/boltstream",
"name": "boltstream"
},
{
"language": "Python",
"id": 316899719,
"full_Name": "r0ysue/r0capture",
"name": "r0capture"
}
],
[
{
"language": "YARA",
"id": 318029147,
"full_Name": "fireeye/red_team_tool_countermeasures",
"name": "red_team_tool_countermeasures"
}
],
[
{
"language": "TypeScript",
"id": 313443335,
"full_Name": "pmndrs/valtio",
"name": "valtio"
}
]
]
what the form I want is
[
[
{
"language": "Python",
"id": [319029846, 319169382, 316899719],
"full_Name": ["beurtschipper/Depix", "benwilber/boltstream", "r0ysue/r0capture"],
"name": ["Depix", "boltstream", "r0capture"]
}
],
[
{
"language": "YARA",
"id": 318029147,
"full_Name": "fireeye/red_team_tool_countermeasures",
"name": "red_team_tool_countermeasures"
}
],
[
{
"language": "TypeScript",
"id": 313443335,
"full_Name": "pmndrs/valtio",
"name": "valtio"
}
]
]
And this is the code i'm using
public class Items
{
[JsonPropertyName("language")]
public string Language { get; set; }
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("full_name")]
public string Full_Name { get; set; }
public string total_count { get; set; }
}
public class Root
{
[JsonPropertyName("items")]
public List<Items> Items { get; set; }
}
Root jObj2 = JsonConvert.DeserializeObject<Root>(readerResult);
var result = jObj2.Items.Select(x => new
{
x.Language,
x.Id,
x.Full_Name,
x.Name
}).GroupBy(x => x.Language).ToArray();
return new JsonResult(result);
GroupBy is a good place to start. Once you have the groups, you need to select the individual properties of each group into a new list:
var result = jObj2.Items
.GroupBy(x => x.Language)
.Select(group => new
{
Language = group.Key,
Ids = group.Select(x => x.Id).ToList(),
FullNames = group.Select(x => x.Full_Name).ToList(),
Names = group.Select(x => x.Name).ToList()
})
.ToArray();
Having some problems deserializing JSON in JSON.net.
First of all I am pulling JSON from my source that looks like the following.
{
"guest": {
"id": 11111,
"A": "bla",
"B": "bla",
"C": false,
"credentials": [
{
"id": 222,
"Z": "bla",
"accounts": [
{
"id": 01,
"type": "bla"
}
]
},
{
"id": 222,
"Z": "bla",
"accounts": [
{
"id": 02,
"type": "bla"
}
]
},
{
"id": 333,
"Z": "bla",
"accounts": [
{
"id": 03,
"type": "bla"
},
{
"id": 04,
"type": "bla"
},
{
"id": 05,
"type": "bla"
},
]
},
]
}
}
Within my code I have the following classes
public class guest
{
public int id { get; set; }
public string A { get; set; }
public string B { get; set; }
public bool C { get; set; }
public IList<credentials> credentials { get; set; }
}
public class credentials
{
public int id { get; set; }
public string Z { get; set; }
public IList<accounts> accounts { get; set; }
}
public class accounts
{
public int id { get; set; }
public string type { get; set; }
}
From this point I get my JSON from an HttpWebResponse and deserialize.
var httpResponseGetResponse = (HttpWebResponse)httpWebRequestGetResponse.GetResponse();
using (var streamReader = new StreamReader(httpResponseGetResponse.GetResponseStream(), Encoding.UTF8))
{
var result = streamReader.ReadToEnd();
guest deseriazedJSON = JsonConvert.DeserializeObject<guest>(result);
}
This ends with everything being NULL. Am I blind and missing something in the JSON.net docs?
Appreciate any help and thank you in advance.
You have an object with a single property named guest on a root level of your JSON. So it can be deserialized in next scenario:
public class Response
{
public guest guest { get; set; }
}
...
var httpResponseGetResponse = (HttpWebResponse)httpWebRequestGetResponse.GetResponse();
using (var streamReader = new StreamReader(httpResponseGetResponse.GetResponseStream(), Encoding.UTF8))
{
var result = streamReader.ReadToEnd();
var deseriazedJSON = JsonConvert.DeserializeObject<Response>(result);
}
It's better to change your JSON input to avoid an extra wrapper:
{
"id": 11111,
"A": "bla",
"B": "bla",
"C": false,
"credentials": [
{
"id": 222,
"Z": "bla"
"accounts": [
{
"id": 01,
"type": "bla"
}
]
},
{
"id": 222,
"Z": "bla"
"accounts": [
{
"id": 02,
"type": "bla"
}
]
},
{
"id": 333,
"Z": "bla"
"accounts": [
{
"id": 03,
"type": "bla"
},
{
"id": 04,
"type": "bla"
},
{
"id": 05,
"type": "bla"
},
]
},
]
}
I am trying to de-serialize this json string:
{"PatientData":[
{
"device": {
"serial": "M01106798",
"manufacturer": "Nipro",
"model": "TrueResult",
"first_value_at": "2010-07-17T22:39:00",
"last_value_at": "2010-09-30T11:18:00",
"supports_glucose": "no",
"supports_cgm": "no",
"supports_insulin": "no",
"supports_carb": "no"
},
"data": []
},
{
"device": {
"serial": "59-50889-10",
"manufacturer": "Animas",
"model": "IR1200",
"first_value_at": "2014-02-07T11:46:00",
"last_value_at": "2014-03-27T10:38:00",
"supports_glucose": "no",
"supports_cgm": "no",
"supports_insulin": "no",
"supports_carb": "no"
},
"data": [
{
"type": "insulin_bolus",
"created_at": "2014-02-07T23:42:00",
"unit": "U",
"total_value": 0.9,
"spike_value": 0.9,
"flags": [
{
"flag": 1008,
"description": "Bolus inactive"
}
]
},
{
"type": "insulin_basal",
"created_at": "2014-02-08T00:01:00",
"value": 0.175,
"unit": "U/h",
"flags": []
},
{
"type": "insulin_basal",
"created_at": "2014-02-08T05:01:00",
"value": 0.225,
"unit": "U/h",
"flags": []
},
{
"type": "insulin_bolus",
"created_at": "2014-02-08T07:42:00",
"unit": "U",
"total_value": 2.6,
"duration": 1800,
"flags": []
},
{
"type": "insulin_bolus",
"created_at": "2014-02-08T09:38:00",
"unit": "U",
"total_value": 0.3,
"spike_value": 0.3,
"flags": [
{
"flag": 1008,
"description": "Bolus inactive"
}
]
},
{
"type": "glucose",
"created_at": "2014-03-27T12:55:18",
"value": 33.167,
"unit": "mmol/l",
"flags": []
}
]
}
]}
by using classes generated from json2csharp like this
public class ObjPatientData
{
public class Device
{
public string serial { get; set; }
public string manufacturer { get; set; }
public string model { get; set; }
public string first_value_at { get; set; }
public string last_value_at { get; set; }
public string supports_glucose { get; set; }
public string supports_cgm { get; set; }
public string supports_insulin { get; set; }
public string supports_carb { get; set; }
}
public class PatientData
{
public Device device { get; set; }
public List<object> data { get; set; }
}
public class RootObject
{
public List<PatientData> PatientData { get; set; }
}
}
and calling it like this:
LPatientData = new List<ObjPatientData.RootObject>();
LPatientData = JsonConvert.DeserializeObject<List<ObjPatientData.RootObject>>(Json);
but I get a list of empty objects; any help will be appreciated.
Thanks!
please note that
Based on the above classes, I solved the issue by returning a list of "PatientData" objects rather than a list of "RootObjects" and using a Jarray.Parse(Json) in this way:
ObjPatientData.RootObject Root = new ObjPatientData.RootObject();
var jArray = JArray.Parse(Json);
Root.PatientData = jArray.ToObject<List<ObjPatientData.PatientData>>();
I think following the code will work.
string json = "{\"PatientData\":[{\"device\": {\"serial\": \"M01106798\",\"manufacturer\": \"Nipro\",\"model\": \"TrueResult\",\"first_value_at\": \"2010-07-17T22:39:00\",\"last_value_at\": \"2010-09-30T11:18:00\",\"supports_glucose\": \"no\",\"supports_cgm\": \"no\",\"supports_insulin\": \"no\",\"supports_carb\": \"no\"},\"data\": []},{\"device\": {\"serial\": \"59-50889-10\",\"manufacturer\": \"Animas\",\"model\": \"IR1200\",\"first_value_at\": \"2014-02-07T11:46:00\",\"last_value_at\": \"2014-03-27T10:38:00\",\"supports_glucose\": \"no\",\"supports_cgm\": \"no\",\"supports_insulin\": \"no\",\"supports_carb\": \"no\"},\"data\": [ {\"type\": \"insulin_bolus\",\"created_at\": \"2014-02-07T23:42:00\",\"unit\": \"U\",\"total_value\": 0.9,\"spike_value\": 0.9,\"flags\": [{\"flag\": 1008,\"description\": \"Bolus inactive\"}]},{\"type\": \"insulin_basal\",\"created_at\": \"2014-02-08T00:01:00\",\"value\": 0.175,\"unit\": \"U/h\",\"flags\": []},{\"type\": \"insulin_basal\",\"created_at\": \"2014-02-08T05:01:00\",\"value\": 0.225,\"unit\": \"U/h\",\"flags\": []},{\"type\": \"insulin_bolus\",\"created_at\": \"2014-02-08T07:42:00\",\"unit\": \"U\",\"total_value\": 2.6,\"duration\": 1800,\"flags\": []},{\"type\": \"insulin_bolus\",\"created_at\": \"2014-02-08T09:38:00\",\"unit\": \"U\",\"total_value\": 0.3,\"spike_value\": 0.3,\"flags\": [{\"flag\": 1008,\"description\": \"Bolus inactive\"}]}, {\"type\": \"glucose\",\"created_at\": \"2014-03-27T12:55:18\",\"value\": 33.167,\"unit\": \"mmol/l\",\"flags\": []}]}]}";
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
RootObject rootObject = javaScriptSerializer.Deserialize<RootObject>(json);