C# Parse Json with multiple objects and arrays newtonsoft - c#

I'm attempting to parse a rather convoluted/unnecessarily complicated JSON output using newtonsoft in C# however for some reason my parser always returns null. I have searched all over SO and cant't seem to find a solution.
An example of a JSON file I'm trying to parse:
{
"success": 1,
"d": {
"gameData": {
"MJ2Y7tDg": {
"scores": [
{
"max": 1.83,
"avg": 1.73,
"rest": 2,
"active": true,
"scoreid": "2c556xv464x0x4vtqc"
},
{
"max": 3.47,
"avg": 3.24,
"rest": 2,
"active": true,
"scoreid": "2c556xv498x0x0"
},
{
"max": 6.06,
"avg": 5.08,
"rest": 1,
"active": true,
"scoreid": "2c556xv464x0x4vtqd"
}
],
"count": 62,
"highlight": [
false,
true
]
},
"jZICYUQu": {
"scores": [
{
"max": 2.25,
"avg": 2.13,
"rest": null,
"active": true,
"scoreid": "2c5guxv464x0x4vuiv"
},
{
"max": 3.55,
"avg": 3.29,
"rest": null,
"active": true,
"scoreid": "2c5guxv498x0x0"
},
{
"max": 3.9,
"avg": 3.33,
"rest": null,
"active": true,
"scoreid": "2c5guxv464x0x4vuj0"
}
],
"count": 62,
"highlight": [
false,
false
]
}
}
}
}
This is what i have so far, I am very new to JSON wrangling :)
public class RootObject
{
public int success { get; set; }
public List<d> d { get; set; }
}
public class d
{
public List<gameData> gameData { get; set; }
}
public class gameData
{
public IDictionary<string, Score> gameData{ get; set; }
public List<scores[]> GameList;
}
public class Score
{
public double max { get; set; }
public double avg { get; set; }
public int rest { get; set; }
public bool active { get; set; }
public string scoreid { get; set; }
}
Anyone with more JSON wrangling experience know how to get this working?
Thankyou in advanced.
P.S I am currently in high school, learning C#

The parser returns null because structure of your classes doesn't correctly resemble the structure of JSON. The correct structure of classes would be:
public class RootObject
{
public int success { get; set; }
public Class_d d { get; set; }
}
public class Class_d
{
public Dictionary<string, GameData> gameData { get; set; }
}
public class GameData
{
public List<Score> scores { get; set; }
public int count { get; set; }
public bool[] highlight { get; set; }
}
public class Score
{
public decimal max { get; set; }
public decimal avg { get; set; }
public int? rest { get; set; }
public bool active { get; set; }
public string scoreid { get; set; }
}
and you can use it as follows:
string json = "..."; // the JSON in your example
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);

Related

Importing Json to objects in C#

I have been working trying to import a list of objects from Json to C#.
The Json structure is:
"meta": {
"file_version": 11,
"machine_number": 210xxxxx,
"software": {
"software_date": "",
"software_version": ""
},
"saved": {
"user": "Bxxxxxx",
"date": "20220810",
"time": "132156"
},
"application": {
"name": "Support",
"type": "xxxxx_Support"
},
"validity": {
"machine_model": "xxx",
"arm_assembly": "xxx",
"boom_pedestal": "xxx"
}
},
"data": {
"data532": {
"number": 54,
"name": "Abstützung vorne - zulässige vertikale Beinkraft (P1.Q1)",
"format": 0,
"digit": 0,
"unit": 10,
"category": 0,
"min": 0,
"max": 1000000,
"value": 225000,
"hexvalue": "0x00036EE8",
"binvalue": "0b00000000000000110110111011101000"
},
"data533": {
"number": 55,
"name": "Abstützung vorne - zulässige vertikale Beinkraft (P1.Q2)",
"format": 0,
"digit": 0,
"unit": 10,
"category": 0,
"min": 0,
"max": 1000000,
"value": 0,
"hexvalue": "0x00000000",
"binvalue": "0b00000000000000000000000000000000"
.
.
.
.
.
My problem is that I need to set up the objects DataXXX in C#.
Im trying with:
var dataconfig = JsonConvert.DeserializeObject<Data>(jsonfile);
Where class Data is
public class Data
{
public int number { get; set; }
public string name { get; set; }
public int format { get; set; }
public int digit { get; set; }
public int unit { get; set; }
public int category { get; set; }
public int min { get; set; }
public int max { get; set; }
public int value { get; set; }
public string hexvalue { get; set; }
public string binvalue { get; set; }
}
But my dataXXX is inside another object called Data so the code is not working. And it's not a list also.
In Newtonsoft.Json, there are two API's, one high-level (JsonConvert) and one low-level (Linq-to-Json). JsonConvert is great for parsing if the data matches the C# class structures you have. Linq-to-Json is great for custom processing and flexibility.
In your case, since your property names have numbers in them that you need to standardize to match C# classes, you probably need to use Linq-to-Json. This parses JSON into objects similar to a Dictionary. Here are the intro docs.
If you need only a data part, you can parse the json at first, after this you can deserialize any part
var jsonParsed = JObject.Parse(jsonFile);
Dictionary<string,Data> dataconfig = jsonParsed["data"].ToObject<Dictionary<string,Data>>();
you should use Dictionary
public class Data {
public Dictionary<string,DataModel> data {get; set;}
}
public class DataModel {
public int number { get; set; }
public string name { get; set; }
public int format { get; set; }
public int digit { get; set; }
public int unit { get; set; }
public int category { get; set; }
public int min { get; set; }
public int max { get; set; }
public int value { get; set; }
public string hexvalue { get; set; }
public string binvalue { get; set; }
}
with Newtonsoft:
JsonConvert.DeserializeObject<Data>(jsonfile); //jsonfile must be includes data.
with System.Text.Json
JsonSerializer.Deserialize<Data>(jsonfile);

How can i improve filter on JSON?

As a title, i'm trying to access some child by following solution from this thread C# JSON.Net parse and get list of all elements matching a value using LINQ .
Here is my code
var result = await response.Content.ReadAsStringAsync();
var jsonData = (JObject)JsonConvert.DeserializeObject(result);
var doc = (JContainer)jsonData["symbols"];
var results = doc.Descendants()
.OfType<JObject>()
.Where(x => x["filterType"] != null &&
x["filterType"].Value<string>() == "MARKET_LOT_SIZE").ToList();
Result is pretty good so far, Here is sample result what i get from trial and error
{
"stepSize": "0.001",
"filterType": "MARKET_LOT_SIZE",
"maxQty": "120",
"minQty": "0.001"
},
{
"stepSize": "0.001",
"filterType": "MARKET_LOT_SIZE",
"maxQty": "140",
"minQty": "0.002"
}
It turn out that result is skip a lot of child to check, but that's not what i expected
i still expect to check upper child to make sure i access child correctly.
Here is real response
{
"timezone": "UTC",
"serverTime": 1660492828507,
"futuresType": "U_MARGINED",
"rateLimits": [
{
"rateLimitType": "REQUEST_WEIGHT",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 2400
},
{
"rateLimitType": "ORDERS",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 1200
},
{
"rateLimitType": "ORDERS",
"interval": "SECOND",
"intervalNum": 10,
"limit": 300
}
],
"exchangeFilters": [],
"assets": [
{
"asset": "USDT",
"marginAvailable": true,
"autoAssetExchange": "-10000"
},
{
"asset": "BTC",
"marginAvailable": true,
"autoAssetExchange": "-0.00100000"
},
{
"asset": "BNB",
"marginAvailable": true,
"autoAssetExchange": "-10"
},
{
"asset": "ETH",
"marginAvailable": true,
"autoAssetExchange": "-5"
},
{
"asset": "XRP",
"marginAvailable": true,
"autoAssetExchange": "0"
},
{
"asset": "ADA",
"marginAvailable": true,
"autoAssetExchange": "0"
},
{
"asset": "USDC",
"marginAvailable": true,
"autoAssetExchange": "-10000"
},
{
"asset": "DOT",
"marginAvailable": true,
"autoAssetExchange": "0"
},
{
"asset": "SOL",
"marginAvailable": true,
"autoAssetExchange": "0"
},
{
"asset": "BUSD",
"marginAvailable": true,
"autoAssetExchange": "-10000"
}
],
"symbols": [
{
"symbol": "BTCUSDT",
"pair": "BTCUSDT",
"contractType": "PERPETUAL",
"deliveryDate": 4133404800000,
"onboardDate": 1569398400000,
"status": "TRADING",
"maintMarginPercent": "2.5000",
"requiredMarginPercent": "5.0000",
"baseAsset": "BTC",
"quoteAsset": "USDT",
"marginAsset": "USDT",
"pricePrecision": 2,
"quantityPrecision": 3,
"baseAssetPrecision": 8,
"quotePrecision": 8,
"underlyingType": "COIN",
"underlyingSubType": [
"PoW"
],
"settlePlan": 0,
"triggerProtect": "0.0500",
"liquidationFee": "0.015000",
"marketTakeBound": "0.05",
"filters": [
{
"minPrice": "556.80",
"maxPrice": "4529764",
"filterType": "PRICE_FILTER",
"tickSize": "0.10"
},
{
"stepSize": "0.001",
"filterType": "LOT_SIZE",
"maxQty": "1000",
"minQty": "0.001"
},
{
"stepSize": "0.001",
"filterType": "MARKET_LOT_SIZE",
"maxQty": "120",
"minQty": "0.001"
},
{
"limit": 200,
"filterType": "MAX_NUM_ORDERS"
},
{
"limit": 10,
"filterType": "MAX_NUM_ALGO_ORDERS"
},
{
"notional": "5",
"filterType": "MIN_NOTIONAL"
},
{
"multiplierDown": "0.9500",
"multiplierUp": "1.0500",
"multiplierDecimal": "4",
"filterType": "PERCENT_PRICE"
}
],
"orderTypes": [
"LIMIT",
"MARKET",
"STOP",
"STOP_MARKET",
"TAKE_PROFIT",
"TAKE_PROFIT_MARKET",
"TRAILING_STOP_MARKET"
],
"timeInForce": [
"GTC",
"IOC",
"FOK",
"GTX"
]
},
{
"symbol": "ETHUSDT",
"pair": "ETHUSDT",
"contractType": "PERPETUAL",
"deliveryDate": 4133404800000,
"onboardDate": 1569398400000,
"status": "TRADING",
"maintMarginPercent": "2.5000",
"requiredMarginPercent": "5.0000",
"baseAsset": "ETH",
"quoteAsset": "USDT",
"marginAsset": "USDT",
"pricePrecision": 2,
"quantityPrecision": 3,
"baseAssetPrecision": 8,
"quotePrecision": 8,
"underlyingType": "COIN",
"underlyingSubType": [
"Layer-1"
],
"settlePlan": 0,
"triggerProtect": "0.0500",
"liquidationFee": "0.015000",
"marketTakeBound": "0.05",
"filters": [
{
"minPrice": "39.86",
"maxPrice": "306177",
"filterType": "PRICE_FILTER",
"tickSize": "0.01"
},
{
"stepSize": "0.001",
"filterType": "LOT_SIZE",
"maxQty": "10000",
"minQty": "0.001"
},
{
"stepSize": "0.001",
"filterType": "MARKET_LOT_SIZE",
"maxQty": "2000",
"minQty": "0.001"
},
{
"limit": 200,
"filterType": "MAX_NUM_ORDERS"
},
{
"limit": 10,
"filterType": "MAX_NUM_ALGO_ORDERS"
},
{
"notional": "5",
"filterType": "MIN_NOTIONAL"
},
{
"multiplierDown": "0.9500",
"multiplierUp": "1.0500",
"multiplierDecimal": "4",
"filterType": "PERCENT_PRICE"
}
],
"orderTypes": [
"LIMIT",
"MARKET",
"STOP",
"STOP_MARKET",
"TAKE_PROFIT",
"TAKE_PROFIT_MARKET",
"TRAILING_STOP_MARKET"
],
"timeInForce": [
"GTC",
"IOC",
"FOK",
"GTX"
]
}
]
}
I want to get maxQty of MARKET_LOT_SIZE where symbol is BTCUSDT and contractType is PERPETUAL. What should i add more filter on this
For your requirement I suggest to create a class and use LINQ on top of that. This will help you in adding conditions quickly
Step1: use json2csharp to convert the json to C# Model
Step2:DeserializeObject using Newtonsoft.JsonConvert
Step3: Add LINQ to get desired output
//STEP2
var doc = JsonConvert.DeserializeObject<Root>(jsonData);
//STEP3
var maxQty = doc.symbols.Where(s => s.symbol == "BTCUSDT" && s.contractType == "PERPETUAL")
.SelectMany(x => x.filters)
.Where(y => y.filterType == "MARKET_LOT_SIZE")
.Max(x => x.maxQty);
//STEP1
public class Asset
{
public string asset { get; set; }
public bool marginAvailable { get; set; }
public string autoAssetExchange { get; set; }
}
public class Filter
{
public string minPrice { get; set; }
public string maxPrice { get; set; }
public string filterType { get; set; }
public string tickSize { get; set; }
public string stepSize { get; set; }
public string maxQty { get; set; }
public string minQty { get; set; }
public int? limit { get; set; }
public string notional { get; set; }
public string multiplierDown { get; set; }
public string multiplierUp { get; set; }
public string multiplierDecimal { get; set; }
}
public class RateLimit
{
public string rateLimitType { get; set; }
public string interval { get; set; }
public int intervalNum { get; set; }
public int limit { get; set; }
}
public class Root
{
public string timezone { get; set; }
public long serverTime { get; set; }
public string futuresType { get; set; }
public List<RateLimit> rateLimits { get; set; }
public List<object> exchangeFilters { get; set; }
public List<Asset> assets { get; set; }
public List<Symbol> symbols { get; set; }
}
public class Symbol
{
public string symbol { get; set; }
public string pair { get; set; }
public string contractType { get; set; }
public object deliveryDate { get; set; }
public object onboardDate { get; set; }
public string status { get; set; }
public string maintMarginPercent { get; set; }
public string requiredMarginPercent { get; set; }
public string baseAsset { get; set; }
public string quoteAsset { get; set; }
public string marginAsset { get; set; }
public int pricePrecision { get; set; }
public int quantityPrecision { get; set; }
public int baseAssetPrecision { get; set; }
public int quotePrecision { get; set; }
public string underlyingType { get; set; }
public List<string> underlyingSubType { get; set; }
public int settlePlan { get; set; }
public string triggerProtect { get; set; }
public string liquidationFee { get; set; }
public string marketTakeBound { get; set; }
public List<Filter> filters { get; set; }
public List<string> orderTypes { get; set; }
public List<string> timeInForce { get; set; }
}

Deserializing object leads to null variables inside object

I am trying to deserialize a object in C#, using NewtonSoft framework fro json handling. This is my code.
Brief Explanation
Essentially, I am creating a api call to the login endpoint to authenticate my user (this works), I need to extract the bearer token from the api call which returns a UserResponseDTO, this DTO contains the AuthToken attribute which I need to access, to pass my test cases.
Now this is the code of my test case.
[Fact]
public async void SuccessfulGetUserDetails()
{
//Arrange
//Arrange
var content = JsonConvert.SerializeObject(success); //Prepare payload
var buffer = System.Text.Encoding.UTF8.GetBytes(content);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //Set type to Json
//Act
var result = await _client.PostAsync("http://localhost:5000/api/Security/login", byteContent); //Send Request
var jsonstring = result.Content.ReadAsStringAsync().Result; //Get JSON String
UserResponseDTO dto = new UserResponseDTO();
dto = JsonConvert.DeserializeObject<UserResponseDTO>(jsonstring); //Deserialize
Assert.Equal(dto,null);
}
Now my last Assert check is to check if the DTO object is null....its not, but the values inside it are.
This is the UserResponseDTO
public class UserResponseDTO
{
public int UserId { get; set; }
public string AuthToken { get; set; }
public string UserName { get; set; }
public string FullName { get; set; }
public string Unit { get; set; }
public string IsActive { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
public List<UserRole> UserRole { get; set; }
public List<Menus> Menus { get; set;}
}
public class UserRole
{
public Role Role { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public int ApplicationId { get; set; }
public string RoleDescription { get; set; }
public virtual List<RolePermission> RolePermission { get; set; }
public List<RoleMenu> RoleMenu { get; set; }
}
public class RoleMenu
{
public int RoleMenuId { get; set; }
public bool IsDefault { get; set; }
public virtual Menu Menu { get; set; }
}
public class RolePermission
{
public int RolePermissionId { get; set; }
public Permission Permission { get; set; }
}
public class Permission
{
public int PermissionId { get; set; }
public string Name { get; set; }
}
public class Menu
{
public int MenuId { get; set; }
public string Urlprefix { get; set; }
public string Url { get; set; }
public string Description { get; set; }
public bool IsParent { get; set; }
public bool IsActive { get; set; }
public int? ParentMenu { get; set; }
public string HtmlBody { get; set; }
public string CssClass { get; set; }
}
public class Menus
{
public bool isExternal { get; set; }
public string cssClass { get; set; }
public string routeLink { get; set; }
public string menuText { get; set; }
public List<SubMenuItems> subMenuItems { get; set; } = new List<SubMenuItems>();
}
public class SubMenuItems
{
public string routeLink { get; set; }
public string menuText { get; set; }
public string cssClass { get; set; }
}
Last but not least, I have noticed
THE CORRECT Json String is being returned however it is not being deserializd properly into a UserResponseDTO Object. And the values inside the DTO are all null.
What can I do to resolve this issue?
He is the JSON that is being returned in JSON String
Code of JSON as requested
"loginResponse": "Authenticated",
"userDetails": {
"userId": 3,
"authToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNjIzMDM2OTkxLCJleHAiOjE2MjMwNDA1OTEsImlhdCI6MTYyMzAzNjk5MX0.wwIJ93syFnpcvjtw_Sj1s4uCtYPUtoROmwF3jkDZWo0",
"userName": "admin",
"fullName": "REDACTED",
"unit": null,
"isActive": "1",
"mobile": "+REDACTED",
"email": "REDACTED",
"userRole": [
{
"role": {
"roleId": 1,
"applicationId": 1,
"roleDescription": "Administrator",
"rolePermission": [
{
"rolePermissionId": 0,
"permission": {
"permissionId": 1,
"name": "CanApprove"
}
},
{
"rolePermissionId": 0,
"permission": {
"permissionId": 2,
"name": "CanReject"
}
},
{
"rolePermissionId": 0,
"permission": {
"permissionId": 3,
"name": "CanReview"
}
},
{
"rolePermissionId": 0,
"permission": {
"permissionId": 4,
"name": "CanDownload"
}
}
],
"roleMenu": [
{
"roleMenuId": 1,
"isDefault": true,
"menu": {
"menuId": 1,
"urlprefix": "UI",
"url": "worklist",
"description": "Menu",
"isParent": true,
"isActive": true,
"parentMenu": null,
"htmlBody": "<li><i class=\"fa fa-cog\"></i><span class=\"nav-label\">HEADING</span></li>",
"cssClass": "receipt"
}
},
{
"roleMenuId": 2,
"isDefault": false,
"menu": {
"menuId": 2,
"urlprefix": "UI",
"url": "reports",
"description": "Link 1",
"isParent": false,
"isActive": true,
"parentMenu": 1,
"htmlBody": "<li><i class=\"fa fa-plug\"></i><span class=\"nav-label\">HEADING</span></li>",
"cssClass": "fact_check"
}
},
{
"roleMenuId": 3,
"isDefault": false,
"menu": {
"menuId": 3,
"urlprefix": "UI",
"url": "generatefile",
"description": "Link 2",
"isParent": false,
"isActive": true,
"parentMenu": 1,
"htmlBody": "<li>HEADING</li>",
"cssClass": "file_present"
}
},
{
"roleMenuId": 9,
"isDefault": false,
"menu": {
"menuId": 4,
"urlprefix": "UI",
"url": "globalsearch",
"description": "Global Search",
"isParent": true,
"isActive": true,
"parentMenu": null,
"htmlBody": "<li>HEADING</li>",
"cssClass": "search"
}
}
]
}
}
],
"menus": [
{
"isExternal": false,
"cssClass": "receipt",
"routeLink": "worklist",
"menuText": "Menu",
"subMenuItems": [
{
"routeLink": "reports",
"menuText": "Link 1",
"cssClass": "fact_check"
},
{
"routeLink": "generatefile",
"menuText": "Link 2",
"cssClass": "file_present"
}
]
},
{
"isExternal": false,
"cssClass": "search",
"routeLink": "globalsearch",
"menuText": "Global Search",
"subMenuItems": []
}
]
}
}
Your json does not match the UserResponseDTO, you need add matched model like:
public class ResponseModel
{
public string LoginResponse { get; set; }
public UserResponseDTO UserDetails { get; set; }
}
If you do not want to add the response model, you need modify the json string to read userDetails:
//1. get the json string
string json = System.IO.File.ReadAllText("test.json");
//2. convert to JObject
var model = JObject.Parse(json);
//3. get userDetails json string
string jsonstring = model["userDetails"].ToString();
UserResponseDTO dto = new UserResponseDTO();
dto = JsonConvert.DeserializeObject<UserResponseDTO>(jsonstring);

Extract few values from JSON Array

The problem I am facing is that I am getting 0's for the values I ask for in the JSON.
I recently asked a question here about getting specific values from a JSON array response that come from an API.
Now I have a new JSON response from a different route and in there I want one values and its called EntityId its places in a block of Entity See the code for more details, I would like to grab that from this response and place them in a list or Array because it tells me who submitted the assignment in D2L.
UPDATE- After getting comments from a user I used JSON to C# tool to create the full class with all the values but I still get the values as 0,0,0,0.
Right now I am getting 0,0,0,0 values and not getting the actual values if it's possible I would like to grab the whole block on Entity.
JSON
[
{
"Entity": {
"DisplayName": "FullName",
"EntityId": 123,
"EntityType": "User",
"Active": true
},
"Status": 1,
"Feedback": null,
"Submissions": [
{
"Id": 27,
"SubmittedBy": {
"Identifier": "123",
"DisplayName": "FullName"
},
"SubmissionDate": "2019-08-01T15:25:04.130Z",
"Comment": {
"Text": "",
"Html": ""
},
"Files": [
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 1245,
"FileName": "1.2.10.png",
"Size": 144407
},
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 292,
"FileName": "1.3.8.png",
"Size": 127869
}
]
}
],
"CompletionDate": "2019-08-01T15:25:04.130Z"
},
{
"Entity": {
"DisplayName": "FullName",
"EntityId": 123,
"EntityType": "User",
"Active": true
},
"Status": 1,
"Feedback": null,
"Submissions": [
{
"Id": 41,
"SubmittedBy": {
"Identifier": "123",
"DisplayName": "FullName"
},
"SubmissionDate": "2019-08-03T03:31:43.807Z",
"Comment": {
"Text": " \nAlex",
"Html": "<p></p>\n<p>Alex</p>"
},
"Files": [
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 313,
"FileName": "Capture 1.2.10 Questions.PNG",
"Size": 97722
}
]
}
],
"CompletionDate": "2019-08-03T03:31:43.807Z"
}
]
Classes:
public class Entity
{
public string DisplayName { get; set; }
public int EntityId { get; set; }
public string EntityType { get; set; }
public bool Active { get; set; }
}
public class SubmittedBy
{
public string Identifier { get; set; }
public string DisplayName { get; set; }
}
public class Comment
{
public string Text { get; set; }
public string Html { get; set; }
}
public class File
{
public bool IsRead { get; set; }
public bool IsFlagged { get; set; }
public bool IsDeleted { get; set; }
public int FileId { get; set; }
public string FileName { get; set; }
public int Size { get; set; }
}
public class Submission
{
public int Id { get; set; }
public SubmittedBy SubmittedBy { get; set; }
public DateTime SubmissionDate { get; set; }
public Comment Comment { get; set; }
public IList<File> Files { get; set; }
}
public class Example
{
public Entity Entity { get; set; }
public int Status { get; set; }
public object Feedback { get; set; }
public IList<Submission> Submissions { get; set; }
public DateTime CompletionDate { get; set; }
}
Code:
var request = new RestRequest(string.Format(Link));
request.Method = Method.GET;
authenticator.Authenticate(client, request);
var response = client.Execute(request);
var thisasa = JsonConvert.DeserializeObject<List<Example>>
(response.Content).Select(
o => o.Identifier).ToList();
The Example data model shown in your question already can be used to successfully deserialize the JSON shown. All that's left is to pick out the Entity.EntityId property via a Select:
var thisasa = JsonConvert.DeserializeObject<List<Example>>(response.Content)
.Select(o => o.Entity.EntityId)
.ToList();
Demo fiddle #1 here.
Incidentally, if you only need Entity.EntityId you could simplify your data model as follows:
public class Entity
{
public int EntityId { get; set; }
}
public class Example
{
public Entity Entity { get; set; }
}
Demo fiddle #2 here.
(As an aside, since your Example class corresponds to the documented object Dropbox.EntityDropbox, you might want to rename your type to EntityDropbox for clarity.)

What is the best way to desirialize this string of json?

I was wondering how I could at best deserialize this json string. For doing that I am using Newtonsoft.json as a plugin with Xamarin.
I only need the parts that says "transaction" and the array in it "transactions" in a list.
{
"id": 999,
"transactions": [
{
"order": 1,
"displayName": "01_lgn",
"transaction": {
"id": 7791,
"name": "01_lgn",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}
{
"order": 2,
"displayName": "02",
"transaction": {
"id": 7793,
"name": "02",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}
],
"defies": null,
"state": 1,
"reportDisplayName": "testSomething"
}
What I already have tried is to put it in a strongly typed class and then make a list of it.
public class testTransaction
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("state")]
public int State { get; set; }
[JsonProperty("reportDisplayName")]
public string ReportDisplayName { get; set; }
[JsonProperty("transactions")]
public List<testTransactions> testTransactions { get; set; }
}
public class testTransactions
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description")]
public object Description { get; set; }
[JsonProperty("warning")]
public int Warning { get; set; }
[JsonProperty("poor")]
public int Poor { get; set; }
[JsonProperty("timeOut")]
public int TimeOut { get; set; }
[JsonProperty("tolerated")]
public int Tolerated { get; set; }
[JsonProperty("frustrated")]
public int Frustrated { get; set; }
[JsonProperty("state")]
public int State { get; set; }
[JsonProperty("includeInThroughputCalculation")]
public bool IncludeInThroughputCalculation { get; set; }
}
But when I try to deserialize it in this way the "searchResult" is empty and I see that nothing is added to the list.
var bleh = jsonstring;
JObject parsedketenObject = JObject.Parse(bleh);
IList<JToken> jTokenResults1 = parsedketenObject;
IList<JToken> jTokenResults2 = parsedketenObject ["transactions"].Children ().ToList ();
IList<JToken> jTokenResults3 = parsedketenObject["transactions"][0]["transaction"].Children().ToList();
_Transactions_list = new List<testTransaction>();
foreach (JToken result in jTokenResults2)
{
testTransaction searchResult = JsonConvert.DeserializeObject<testTransaction>(result.ToString());
_Transactions_list.Add(searchResult);
}
Firstly, the JSON seems to be malformed, you are missing comma.
{
"id": 999,
"transactions": [
{
"order": 1,
"displayName": "01_lgn",
"transaction": {
"id": 7791,
"name": "01_lgn",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}, <-------- HERE
{
"order": 2,
"displayName": "02",
"transaction": {
"id": 7793,
"name": "02",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}
],
"defies": null,
"state": 1,
"reportDisplayName": "testSomething"
}
Additionally, try these for your POCO instead:
public class TransactionDetails
{
public int id { get; set; }
public string name { get; set; }
public object description { get; set; }
public int warning { get; set; }
public int poor { get; set; }
public int timeOut { get; set; }
public int tolerated { get; set; }
public int frustrated { get; set; }
public int state { get; set; }
public bool includeInThroughputCalculation { get; set; }
}
public class Transaction
{
public int order { get; set; }
public string displayName { get; set; }
public TransactionDetails transaction { get; set; }
}
public class RootObject
{
public int id { get; set; }
public List<Transaction> transactions { get; set; }
public object defies { get; set; }
public int state { get; set; }
public string reportDisplayName { get; set; }
}
Then you can use
var x = JsonConvert.DeserializeObject<RootObject>(blah);
x will contain transactions, which is already a list.
This method is not strongly typed, but it will work:
var jsonString = GetTheJson(); // however you get your json
dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
foreach (var txn in jsonObject.transactions)
{
Console.WriteLine("{0} {1} {2}", txn.order, txn.displayName, txn.transaction.id);
}
The best way to serialize/deserialize a json string to json object is using Google Gson library. You should create DTO files and use its type to serialize the string.
The documentation can be found here: https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html

Categories

Resources