Remove the property name from JSON Array in C# - c#

I've a JSON object containing an array like this:
{
"CustRecord": [
{
"ID": "40274",
"Currency": "USD",
"CustomerNumber": "123456",
"CustomerName": "contoso"
},
{
"ID": "40275",
"Currency": "USD",
"CustomerNumber": "123456",
"CustomerName": "contoso"
}
]
}
and I want to remove the property name "CustRecord" from JSON to create the following output using C#.
How can I achieve this?
[
{
"ID": "40274",
"Currency": "USD",
"CustomerNumber": "123456",
"CustomerName": "contoso"
},
{
"ID": "40275",
"Currency": "USD",
"CustomerNumber": "123456",
"CustomerName": "contoso"
}
]

In .NET 6 you can use the new "System.Text.Json.Nodes" namespace. It introduced JsonObject and JsonNode. You can do the following:
JsonNode original = JsonObject.Parse(jsonString);
string newJson = original["CustRecord"].ToJsonString();
If you want the serialized result to be indented (pretty) Json, then you can pass JsonSerializerOptions to ToJsonString():
string newJson = original["CustRecord"].ToJsonString(new JsonSerializerOptions
{
WriteIndented = true
});

try this
var newJson=JObject.Parse(json)["CustRecord"].ToString();
or the most efficient way
json=json.Substring(0,json.Length-1).Substring(json.IndexOf(":")+1);
result
[
{
"ID": "40274",
"Currency": "USD",
"CustomerNumber": "123456",
"CustomerName": "contoso"
},
{
"ID": "40275",
"Currency": "USD",
"CustomerNumber": "123456",
"CustomerName": "contoso"
}
]
but if you need to deserialize json, not just parse , the best way would be
var customerRecord =JObject.Parse(json)["CustRecord"].ToObject<CustomerRecord>();
class
public class CustomerRecord
{
public string ID { get; set; }
public string Currency { get; set; }
public string CustomerNumber { get; set; }
public string CustomerName { get; set; }
}

Related

How to group JSON data by ID in C#

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)
}

I'm not able to convert IRestresponse to a object. What am i missing?

I hope someone can help me out here, because I'm pretty stuck ;)
I do not understand the error I'm getting:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'OdosTest.OdosRecord' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Isn't my json respone (see in the bottom) okay?
I'm trying to deserialize my IRestResponse to a object, but with no luck. The classes should be finde, or where am I wrong?
Here is my code:
using System;
using RestSharp;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace OdosTest
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://triscan.odosolutions.com/api/v1/streams");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic HIDDEN");
IRestResponse response = client.Execute(request);
var odosRecord = JsonConvert.DeserializeObject<OdosRecord>(response.Content);
//Console.WriteLine(response.Content);
}
}
public class OdosRecord
{
public int version { get; set; }
public string id { get; set; }
public int loggerImei { get; set; }
public string vin { get; set; }
public DateTime startTime { get; set; }
public Signal[] signals { get; set; }
}
public class Signal
{
public string source { get; set; }
public string name { get; set; }
public string displayName { get; set; }
public string number { get; set; }
public string unit { get; set; }
public bool isNumericComplement { get; set; }
public Value[] values { get; set; }
}
public class Value
{
public DateTime timestamp { get; set; }
public string value { get; set; }
}
}
Here is the response I get:
[
{
"version": 1,
"id": "0414bafa-39fe-4924-a1e3-f2180161f058",
"loggerImei": 1000606,
"vin": "WF0VXXGCEVFY08396",
"startTime": "2020-07-03T12:59:04.000345Z",
"signals": [
{
"source": "OBD",
"name": "01_42_CMV",
"displayName": "CMV",
"number": "0142",
"unit": "V",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "13.78"
}
]
},
{
"source": "OBD",
"name": "DETECTED_PROTOCOL",
"displayName": "DETECTED_PROTOCOL",
"number": "N/A",
"unit": "",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "CAN"
}
]
},
{
"source": "OBD",
"name": "01_31_TravelledDistSinceCodeCleared",
"displayName": "TravelledDistSinceCodeCleared",
"number": "0131",
"unit": "km",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "53749"
}
]
}
]
}
]
Your json contains a List<OdosRecord>, so this should solve the issue:
var odosRecord = JsonConvert.DeserializeObject<List<OdosRecord>>(response.Content);
otherwise you cloud change your json to this (if you are able to change the contract):
{
"version": 1,
"id": "0414bafa-39fe-4924-a1e3-f2180161f058",
"loggerImei": 1000606,
"vin": "WF0VXXGCEVFY08396",
"startTime": "2020-07-03T12:59:04.000345Z",
"signals": [
{
"source": "OBD",
"name": "01_42_CMV",
"displayName": "CMV",
"number": "0142",
"unit": "V",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "13.78"
}
]
},
{
"source": "OBD",
"name": "DETECTED_PROTOCOL",
"displayName": "DETECTED_PROTOCOL",
"number": "N/A",
"unit": "",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "CAN"
}
]
},
{
"source": "OBD",
"name": "01_31_TravelledDistSinceCodeCleared",
"displayName": "TravelledDistSinceCodeCleared",
"number": "0131",
"unit": "km",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "53749"
}
]
}
]
}

Need help deserializing JSON Object returned from API

I have the following JSON Output:
{{
"$type": "Asi.Soa.Core.DataContracts.PagedResult`1[[Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts]], Asi.Contracts",
"Items": {
"$type": "System.Collections.Generic.List`1[[Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts]], mscorlib",
"$values": [
{
"$type": "Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts",
"EntityTypeName": "14",
"Properties": {
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyDataCollection, Asi.Contracts",
"$values": [
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "ResultRow",
"Value": "1"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "Work Phone",
"Value": "(782) 438-7600"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "Email",
"Value": "agsaz#rmax.net"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "Full Name",
"Value": "Agazny"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "iMISId",
"Value": "eg1"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "Preferred Phone",
"Value": "780"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "Organization",
"Value": "Re"
}
]
}
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts",
"EntityTypeName": "14",
"Properties": {
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyDataCollection, Asi.Contracts",
"$values": [
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "ResultRow",
"Value": "2"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "Work Phone",
"Value": "7802"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "Email",
"Value": "aksm"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "Full Name",
"Value": "Aji"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "iMISId",
"Value": "esa"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "Preferred Phone",
"Value": "780"
},
{
"$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
"Name": "Organization",
"Value": "Hom"
}
]
}
}
I am trying to deserialize this response into workable c# objects and POST it to a different API that accepts a totally different format of JSON.
This is my code so far:
using (var client = new HttpClient())
{
// Format headers
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Request token, and append to headers
await AddTokenToHeaders(client);
// Query HTTP Service
var response = await client.GetAsync(baseUrl + "api/IQA?querydocumentversionkey=f2005a6e-7f47-47c3-a7e7-bbd2a7b6ab38");
if (response.IsSuccessStatusCode)
{
var customer = await response.Content.ReadAsStringAsync();
JObject result = JObject.Parse(await response.Content.ReadAsStringAsync());
JArray a = (JArray)result["Items"]["$values"][0]["Properties"];
var test = a.AsJEnumerable();
However, it's not picking up my entire JSON object and I am not able to map it to the properties of my class:
--Update.
I have updated my code and I was able to get the Jarray in the format I wanted, however when I try enumerate by jObject into my List of Class Customer, the properties I try to cast returns nulls.
Thanks for the response. I was able to get the output I was looking for by using the following code. However, attempting to put the output in my List of Customer class with the properties specified however, I am getting nulls on the properties of class Customer.
JObject result = JObject.Parse(await response.Content.ReadAsStringAsync());
JArray a = (JArray)result["Items"]["$values"];
List<Customer> items = ((JArray)a).Select(x => new Customer
{
ResultRow = (string)x["ResultRow"],
WorkPhone = (string)x["Work Phone"],
Email = (string)x["Email"],
FullName = (string)x["Full Name"],
iMISId = (string)x["iMISId"],
PreferredPhone = (string)x["Preferred Phone"],
Organization = (string)x["Organization"]
}).ToList();
public class Customer
{
[JsonProperty("ResultRow")]
public string ResultRow { get; set; }
[JsonProperty("Work Phone")]
public string WorkPhone { get; set; }
[JsonProperty("Email")]
public string Email { get; set; }
[JsonProperty("Full Name")]
public string FullName { get; set; }
[JsonProperty("iMISId")]
public string iMISId { get; set; }
[JsonProperty("Preferred Phone")]
public string PreferredPhone { get; set; }
[JsonProperty("Organization")]
public string Organization { get; set; }
}
There is a mistake in the code you provided. You are trying to cast the Properties into a JArray when it is an object.
If you do want the array in the Properties object, do this:
JArray arr = (JArray)result["Items"]["$values"][0]["Properties"]["$values"];
Otherwise, if you are looking for the Properties object, then you should do this instead:
JObject obj = (JObject)result["Items"]["$values"][0]["Properties"];
Finally, to rebuild the list of Customer instances, you could use the following logic with the static methods:
var customersJson = (JArray)result["Items"]["$values"];
var customers = new List<Customer>();
foreach (JObject o in customersJson)
{
var customerJson = (JArray) o["Properties"]["$values"];
customers.Add(BuildCustomer(customerJson));
}
[...]
private static Customer BuildCustomer(JArray a)
{
return new Customer
{
ResultRow = GetValue(a, "ResultRow"),
WorkPhone = GetValue(a, "Work Phone"),
Email = GetValue(a, "Email"),
FullName = GetValue(a, "Full Name"),
iMISId = GetValue(a, "iMISId"),
PreferredPhone = GetValue(a, "Preferred Phone"),
Organization = GetValue(a, "Organization")
};
}
private static string GetValue(JArray array, string name)
{
JToken obj = array.FirstOrDefault(x => (string) x["Name"] == name);
if (obj == null)
return string.Empty;
return (string) obj["Value"];
}

How do I arrange similar data from multiple json files but in different format?

I am new to JSON and trying to develop a comparison table with data coming from 2 different JSON files as follows.
Json File 1
"data":[
{
"EffectiveDate": "2017-04-01T00:00:00Z",
"IncludedQuantity": 0,
"Category": "VM",
"Id": "d0bf9053",
"Name": "Element1",
"Rates": {
"0": 0.04
},
"Region": "US",
"Status": "Active",
"SubCategory": "S1",
"Tags": [],
"Unit": "Hours"
},
{
"EffectiveDate": "2017-02-01T00:00:00Z",
"IncludedQuantity": 0,
"Category": "DS",
"Id": "8b7672d4",
"Name": "Element2",
"Rates": {
"0": 4.0177
},
"Region": "UK",
"Status": "Active",
"SubCategory": "S2",
"Tags": [],
"Unit": "Days"
}]
Json File 2
"data":{
"d0bf9053":{
"EffectiveDate": "2017-04-01T00:00:00Z",
"IncludedQuantity": 0,
"Category": "VM",
"Id": "d0bf9053",
"Attributes":{
"Name": "Element1",
"Rates": {
"0": 5
},
"Region": "US",
"Status": "Active",
"SubCategory": "S1",
"Tags": [],
"Unit": "Hours"
}
},
"8b7672d4":{
"EffectiveDate": "2017-02-01T00:00:00Z",
"IncludedQuantity": 0,
"Category": "DS",
"Id": "8b7672d4",
"Attributes":{
"Name": "Element2",
"Rates": {
"0": 1
},
"Region": "UK",
"Status": "Active",
"SubCategory": "S2",
"Tags": [],
"Unit": "Days"
}
}}
Now I have to read this data and merge it to create a comparison based on rates and categories. I have created a Dot.Net Console Application and trying to use SQL Server to store the information. Now I am able to read JSON File 1 easily. But I am facing difficulty in storing values from JSON File 2. How do I solve this or am I wrong somewhere.
Thanks in advance.
The problem here is that you have dynamic property names in the second JSON file (Json File 2) and you are probably having trouble deserializing that JSON into a .Net Class, right?
Here are some examples that you can use to deserialize both Json1 and Json2 Types:
public class dataJson1
{
public List<Detail> data { get; set; }
}
public class dataJson2
{
public Dictionary<string, Detail> data { get; set; }
}
public class Detail
{
public DateTime EffectiveDate { get; set; }
public int IncludedQuantity { get; set; }
public string Category { get; set; }
//add the rest of the props here
}
That should get you started, once it's deserialized into those Objects, comparing them should be trivial.

Json.Net deserialize object give me empty object

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);

Categories

Resources