C# JSON.net DeserializeObject<Class> fills up a with null - c#

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"
},
]
},
]
}

Related

Mongodb c# - ReplaceOne create duplicate element '_t' error

I try to make an API using ASP NET CORE 7 and mongodb.
I come with a complicated problem that i simply don't understand.
I got a duplicated element name '_t' error when i get my documents after i used ReplaceOneAsync method.
I have Ship documents using polymorphism as :
using MongoDB.Bson.Serialization.Attributes;
using Shipest.Api.Models.DTO.QueriesDTO;
using Shipest.Api.Utils.ExceptionUtils;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
namespace Shipest.Api.Models.DTO;
[BsonIgnoreExtraElements(true)]
[BsonDiscriminator(Required = true, RootClass = true)]
[BsonKnownTypes(typeof(ProbatioDTO), typeof(SpeculatorDTO), typeof(ExtractorDTO), typeof(ManusDTO))]
[JsonDerivedType(typeof(ProbatioDTO))]
[JsonDerivedType(typeof(SpeculatorDTO))]
[JsonDerivedType(typeof(ExtractorDTO))]
[JsonDerivedType(typeof(ManusDTO))]
public class BaseShipDTO
{
[BsonIgnore]
private string id;
[BsonId]
[BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
public string Id {
get {
if (new Regex("^[0-9a-fA-F]{24}$").IsMatch(id))
return id;
else
throw new ShipestException("Invalid Id : " + id, 400);
}
set => id = value;
}
public string Name { get; set; }
public virtual PlanetGetDTO? Planet { get; set; }
public DateTime Creation_Date { get; set; }
public int Health { get; set; }
public int Max_Health { get; set; }
[BsonElement("_t")]
public ShipType Type { get; set; }
public long? Owner_Id { get; set; }
public PlanetGetDTO? Planet_Arrival { get; set; }
public DateTime? Arrival_Date { get; set; }
public int Speed { get; set; }
public int Energy { get; set; }
public int Max_Energy { get; set; }
public DateTime? Next_Scan_Date { get; set; }
public int Scan_Cost { get; set; }
public DateTime? Next_Heal_Date { get; set; }
public int Creatium_Cost { get; set; }
}
with ShipType enumeration as :
public enum ShipType
{
Manus,
Probatio,
Speculator,
Extractor
}
When i simply query my document using id, all works. Here my aggregation json used :
[
%m,
{
"$lookup": {
"from": "planets",
"localField": "Coordinates",
"foreignField": "_id",
"as": "Planets"
}
},
{
"$lookup": {
"from": "planets",
"as": "Neighbours",
"let": {
"main_x": "$Coordinates.X",
"main_y": "$Coordinates.Y"
},
"pipeline": [
{
"$match": {
"$expr": {
"$or": [
{
"$eq": [
"$_id",
{
"X": {
"$add": [ "$$main_x", 1 ]
},
"Y": {
"$add": [ "$$main_y" ]
}
}
]
},
{
"$eq": [
"$_id",
{
"X": {
"$add": [ "$$main_x", -1 ]
},
"Y": {
"$add": [ "$$main_y" ]
}
}
]
},
{
"$eq": [
"$_id",
{
"X": {
"$add": [ "$$main_x" ]
},
"Y": {
"$add": [ "$$main_y", 1 ]
}
}
]
},
{
"$eq": [
"$_id",
{
"X": {
"$add": [ "$$main_x" ]
},
"Y": {
"$add": [ "$$main_y", -1 ]
}
}
]
}
]
}
}
}
]
}
},
{
"$lookup": {
"from": "planets",
"localField": "Planet_of_Arrival_Coordinate",
"foreignField": "_id",
"as": "planet_of_arrival"
}
},
{
"$lookup": {
"from": "planets",
"as": "Neighbours_Arrival",
"let": {
"main_x": "$Planet_of_Arrival_Coordinate.X",
"main_y": "$Planet_of_Arrival_Coordinate.Y"
},
"pipeline": [
{
"$match": {
"$expr": {
"$or": [
{
"$eq": [
"$_id",
{
"X": {
"$add": [ "$$main_x", 1 ]
},
"Y": {
"$add": [ "$$main_y" ]
}
}
]
},
{
"$eq": [
"$_id",
{
"X": {
"$add": [ "$$main_x", -1 ]
},
"Y": {
"$add": [ "$$main_y" ]
}
}
]
},
{
"$eq": [
"$_id",
{
"X": {
"$add": [ "$$main_x" ]
},
"Y": {
"$add": [ "$$main_y", 1 ]
}
}
]
},
{
"$eq": [
"$_id",
{
"X": {
"$add": [ "$$main_x" ]
},
"Y": {
"$add": [ "$$main_y", -1 ]
}
}
]
}
]
}
}
}
]
}
},
{
"$addFields": {
"Planet": {
"$first": "$Planets"
},
"Planet_Arrival": {
"$first": "$planet_of_arrival"
}
}
},
{
"$addFields":
{
"Planet.Neighbours": "$Neighbours",
"Planet_Arrival.Neighbours": "$Neighbours_Arrival"
}
},
{
"$unset": [
"Coordinates",
"Planet_of_Arrival_Coordinate",
"Planets",
"planet_of_arrival",
"Neighbours_Arrival",
"Neighbours"
]
},
{
"$set":
{
"Planet_Arrival": {
"$cond": {
"if": {
"$eq": [
{
"$type": "$Planet_Arrival._id"
},
"object"
]
},
"then": "$Planet_Arrival",
"else": "$$REMOVE"
}
},
"Planet": {
"$cond": {
"if": {
"$eq": [
{
"$type": "$Planet._id"
},
"object"
]
},
"then": "$Planet",
"else": "$$REMOVE"
}
}
}
}
]
i know my aggregate can surely be simplified but i'm a beginner with these noSQL syntaxe ahah.
And of course %m is replaced in code as :
private string getAggregateWithMatch(string match)
{
return File.ReadAllText(#".\Database\JsonQueries\shipAggregate.json").Replace("%m", match);
}
public async Task<BaseShipDTO?> GetAsync(string shipId)
{
// use the json
var query = getAggregateWithMatch("{'$match': { '_id': ObjectId('" + shipId + "') }}");
var listResulted = await DataBaseUtils.DoGenericAggregate<BaseShipDTO, Ship>(query, _shipsCollection);
return listResulted.FirstOrDefault();
}
and documents that i do tests on it in mongodb is as :
{
"_id": {
"$oid": "63d10256d3d1cc30603cfaf6"
},
"_t": "Speculator",
"Coordinates": {
"X": 12,
"Y": -4
},
"Health": 600,
"Max_Health": 100000,
"Name": "Roger",
"Creation_Date": {
"$date": {
"$numberLong": "1674136353103"
}
},
"Creatium_Cost": 300,
"Energy": 100,
"Max_Energy": 100,
"Next_Scan_Date": null,
"Planet_of_Arrival_Coordinate": {
"X": 13,
"Y": -4
},
"Scan_Cost": 5,
"Speed": 600,
"Next_Heal_Date": {
"$date": {
"$numberLong": "1675610925014"
}
},
"Arrival_Date": null,
"Owner_Id": {
"$numberLong": "279937954565193729"
}
}
so when i change the Health property for exemple, and after that i use this method :
public async Task UpdateAsync(Ship ship)
{
await _shipsCollection.ReplaceOneAsync(s => s._id == ship._id, ship, new ReplaceOptions { IsUpsert = false });
}
i see no change with my document in database except my Health field (and the Health Date, which is normal):
{
"_id": {
"$oid": "63d10256d3d1cc30603cfaf6"
},
"_t": "Speculator",
"Coordinates": {
"X": 12,
"Y": -4
},
"Health": 750,
"Max_Health": 100000,
"Name": "Roger",
"Creation_Date": {
"$date": {
"$numberLong": "1674136353103"
}
},
"Creatium_Cost": 300,
"Energy": 100,
"Max_Energy": 100,
"Next_Scan_Date": null,
"Planet_of_Arrival_Coordinate": {
"X": 13,
"Y": -4
},
"Scan_Cost": 5,
"Speed": 600,
"Next_Heal_Date": {
"$date": {
"$numberLong": "1675611313544"
}
},
"Arrival_Date": null,
"Owner_Id": {
"$numberLong": "279937954565193729"
}
}
But at this point, i get my firstly presented error around _t when i try to re get it using my getAsync method :/ despite the fact that the field '_t' dont change at all.
Thanks you for any help^, sorry for my weird english (i'm french huh) and sorry if i forget useful code parts !
error message after a get on a object who got a replaceOne before
I solved it by removing _t field in my bdd model :
I replace using a model with exact same fields wich my mongo db takes :
public record Ship(
ObjectId _id,
Coordinates? Coordinates,
int Health,
int Max_Health,
string Name,
DateTime Creation_Date,
int Creatium_Cost,
int Energy,
int Max_Energy,
DateTime? Next_Scan_Date,
Coordinates? Planet_of_Arrival_Coordinate,
int Scan_Cost,
string _t,
int Speed,
DateTime? Next_Heal_Date,
DateTime? Arrival_Date,
long? Owner_Id
);
i removed the _t field from it, it cwas causing a weird dual modification on it (on from mongo driver, on from my field)

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

Problems deserializing Newtonsoft JSON in c# returning null

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

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

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