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);
Related
I get the data from the web server as json, but I can't deserialize them and access the keys (eg first_name)
The information is received in the client, but Unfortunately, this code does not print anything in the Unity console
my code :
socket.On("UserList", response =>
{
var result = JsonConvert.DeserializeObject<List<UserClass>>(response.ToString());
var first_name = result[0].first_name;
print(first_name);
});
UserClass :
public class UserClass
{
public string _id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string mobile { get; set; }
public string email { get; set; }
public DateTime createdAt { get; set; }
public DateTime updateAt { get; set; }
public int __v { get; set; }
}
Json that is received in the client :
[
{
"_id": "83ca7d56cbc2b281wd4ee658",
"first_name": "sara",
"last_name": "Paulson",
"mobile": "09323456789",
"email": "sara#gmail.com",
"createdAt": "2023-01-20T12:46:38.384Z",
"updateAt": "2023-01-20T12:46:38.384Z",
"__v": 0
},
{
"_id": "59e41dku510239e83ed7e10m",
"first_name": "Evan",
"last_name": "Peters",
"mobile": "09327931248",
"email": "Evan#gmail.com",
"createdAt": "2023-02-10T10:35:26.687Z",
"updateAt": "2023-02-10T10:35:26.687Z",
"__v": 0
},
{
"_id": "64lm96c57a8a4f289fw0gg66",
"first_name": "Emma",
"last_name": "Roberts",
"mobile": "09325354769",
"email": "Emma#gmail.com",
"createdAt": "2023-01-20T13:11:46.402Z",
"updateAt": "2023-01-20T13:11:46.402Z",
"__v": 0
}
]
How can I access keys of this Json in Unity?
I checked and found that even specifying arrays in JSON works somehow:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
class UserClass
{
public string _id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string mobile { get; set; }
public string email { get; set; }
public DateTime createdAt { get; set; }
public DateTime updateAt { get; set; }
public int __v { get; set; }
}
class UserList
{
public List<UserClass> objs;
}
public class Program
{
public static void Main(string[] args)
{
string response = "{'objs': [{'_id': 1, 'first_name': 'abc'}, {'_id': 2, 'first_name': 'def'}]}";
var result = JsonConvert.DeserializeObject<UserList>(response);
if (result != null)
{
foreach (UserClass u in result.objs)
{
Console.Write(u._id + ',');
Console.WriteLine(u.first_name);
}
}
string response2 = "[{'_id': 1, 'first_name': 'abc'}, {'_id': 2, 'first_name': 'def'}]";
var result2 = JsonConvert.DeserializeObject<List<UserClass>>(response2);
if (result2 != null)
{
for (var i = 0; i < result2.Count; i++)
{
Console.Write(result2[i]._id + ',');
Console.WriteLine(result2[i].first_name);
}
}
}
}
Both ways give same output. https://dotnetfiddle.net/g2Dn1n
The only additional thing I did was to check for returned value. You should use Debug.Log() in Unity to print actual values obtained after deserialization.
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; }
}
Basically I am making an api call I receive the api call in a JSON format and I need to basically filter through the api call to only return the value's for sys_name. I am unsure how to accomplish this as my JsonConvert.DeserializeObject<>() is coming back blank.
{
try
{
using (HttpClient client = GetClient())
{
var response = client.GetAsync("this is the api call but I cleared it as you wont be able to use anyway");
response.Wait();
if (response.Result.IsSuccessStatusCode)
{
var result = await response.Result.Content.ReadAsStringAsync();
Result items = JsonConvert.DeserializeObject<Result>(result);
Console.WriteLine(items.SysName);
return null;
}
};
} catch (Exception ex)
{
_logger.LogWarning(ex, $"Failed to retrieve requested Table |{ex.Message}");
Console.WriteLine(ex.Message);
}
return null;
}
and then I have a wrapper class that I made using jsonutils.com
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class SysPackage
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class SysScope
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class Result
{
[JsonProperty("rec_misc")]
public string RecMisc { get; set; }
[JsonProperty("question")]
public Question Question { get; set; }
[JsonProperty("sys_mod_count")]
public string SysModCount { get; set; }
[JsonProperty("sys_updated_on")]
public string SysUpdatedOn { get; set; }
[JsonProperty("sys_tags")]
public string SysTags { get; set; }
[JsonProperty("sys_class_name")]
public string SysClassName { get; set; }
[JsonProperty("published_ref")]
public string PublishedRef { get; set; }
[JsonProperty("sys_id")]
public string SysId { get; set; }
[JsonProperty("sys_package")]
public SysPackage SysPackage { get; set; }
[JsonProperty("inactive")]
public string Inactive { get; set; }
[JsonProperty("sys_update_name")]
public string SysUpdateName { get; set; }
[JsonProperty("sys_updated_by")]
public string SysUpdatedBy { get; set; }
[JsonProperty("sys_created_on")]
public string SysCreatedOn { get; set; }
[JsonProperty("sys_name")]
public string SysName { get; set; }
[JsonProperty("sys_scope")]
public SysScope SysScope { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("sys_created_by")]
public string SysCreatedBy { get; set; }
[JsonProperty("misc")]
public string Misc { get; set; }
[JsonProperty("order")]
public string Order { get; set; }
[JsonProperty("sys_policy")]
public string SysPolicy { get; set; }
}
public class Wrapper
{
[JsonProperty("result")]
public IList<Result> Result { get; set; }
}
}
Showing that items comes up empty
JSON format I had to edit some of the values and obv its way longer but this should give an idea
{
"result": [
{
"rec_misc": "0",
"question": {
"link": "link goes here",
"value": "494a2"
},
"sys_mod_count": "1",
"sys_updated_on": "2021-11-15 17:18:10",
"sys_tags": "",
"sys_class_name": "question_choice",
"published_ref": "",
"sys_id": "",
"sys_package": {
"link": "link goes here",
"value": "global"
},
"inactive": "false",
"sys_update_name": "question_choice_",
"sys_updated_by": "someone ",
"sys_created_on": "2021-11-15 17:17:35",
"sys_name": "BG Info",
"sys_scope": {
"link": "link goes here",
"value": "global"
},
"text": "BG Info",
"value": "BG Info",
"sys_created_by": "someone",
"misc": "0",
"order": "300",
"sys_policy": ""
},
{
"rec_misc": "0",
"question": {
"link": "link goes here",
"value": "5b42"
},
"sys_mod_count": "0",
"sys_updated_on": "2021-04-14 06:56:39",
"sys_tags": "",
"sys_class_name": "question_choice",
"published_ref": "",
"sys_id": "05c2d",
"sys_package": {
"link": "link goes here",
"value": "global"
},
"inactive": "false",
"sys_update_name": "question_choice_",
"sys_updated_by": "someone",
"sys_created_on": "2021-04-14 06:56:39",
"sys_name": "Baseline (Developer Plus Build Mgr)",
"sys_scope": {
"link": "link goes here",
"value": "global"
},
"text": "Baseline (Developer Plus Build Mgr)",
"value": "baseline",
"sys_created_by": "someone",
"misc": "0",
"order": "300",
"sys_policy": ""
},
Use
Wrapper results = JsonConvert.DeserializeObject<Wrapper>(result);
The response is coming as an array so you have to map the data properly.
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.)
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