I have the simple JSON:
[
{
"new_as_cod": "0010955",
"as_nome": "NAME",
"as_cpf": "1212121212",
"as_email": "IM#UOL.COM.BR",
"as_cep": "88.025-200",
"igr_nome": "1\u00aa IGREJA BATISTA - FLORIANOPOLIS",
"id": "2781",
"valor": "50.00",
"pg_tipo_id": "CC",
"status": "Ativo",
"idstatus": "1"
}
]
... and a C# class generated from here:
public class RootObject
{
public string new_as_cod { get; set; }
public string as_nome { get; set; }
public string as_cpf { get; set; }
public string as_email { get; set; }
public string as_cep { get; set; }
public string igr_nome { get; set; }
public string id { get; set; }
public string valor { get; set; }
public string pg_tipo_id { get; set; }
public string status { get; set; }
public string idstatus { get; set; }
}
I have tried this:
RootObject data = JsonConvert.DeserializeObject<RootObject>(stringdate);
But I get the error:
How can I solve it?
[{ "new_as_cod": "0010955", "as_nome": "NAME", "as_cpf": "1212121212", "as_email": "IM#UOL.COM.BR", "as_cep": "88.025-200", "igr_nome": "1\u00aa IGREJA BATISTA - FLORIANOPOLIS", "id": "2781", "valor": "50.00", "pg_tipo_id": "CC", "status": "Ativo", "idstatus": "1" }]
If it has [] this is a collection.
Try this.
JsonConvert.DeserializeObject<List<RootObject>>(stringdate);
Yes, this JSON is a collection, so the variable needs to be list too.
List<RootObject> data = JsonConvert.DeserializeObject<List<RootObject>>(stringdate);
Related
I have the following JSON string
{
"data": [
{
"symbol": "1COV.GE",
"exposure": "0",
"makerExposure": "-2028",
"takerExposure": "2028",
"makerPnl": "447.6688",
"takerPnl": "-447.6688",
"makerPositions": [
{
"name": "IB_001",
"position": "-2028",
"vwap": "47.41",
"pnl": "447.6688"
}
],
"takerPositions": [
{
"name": "MT5_1",
"position": "2028",
"vwap": "47.41",
"pnl": "-447.6688"
}
]
},
{
"symbol": "A",
"exposure": "0",
"makerExposure": "-10",
"takerExposure": "10",
"makerPnl": "-4.6",
"takerPnl": "4.6",
"makerPositions": [
{
"name": "IB_002",
"position": "-10",
"vwap": "136.78",
"pnl": "-4.6"
}
],
"takerPositions": [
{
"name": "MT5_1",
"position": "10",
"vwap": "136.78",
"pnl": "4.6"
}
],
"total": 2
}
}
And my goal is to serialize it into a List of object from the NODE "Data":
I have the classes that map the data node fields:
public class Positions
{
public string name { get; set; }
public string position { get; set; }
public string vwap { get; set; }
public string pnl { get; set; }
}
public class ExPositions
{
public string symbol { get; set; }
public string exposure { get; set; }
public string makerExposure { get; set; }
public string takerExposure { get; set; }
public string makerPnl { get; set; }
public string takerPnl { get; set; }
public OZPositions makerPositions { get; set; }
public OZPositions takerPositions { get; set; }
}
Do you have any ideas how I can convert the node "data" to list of "ExPositions" objects, eg. List
I've did this but so far it throws an error
var positions = JsonSerializer.Deserialize<ExPositions>(json_string);
There is an error in your json - it's missing a closing ] for the array (I'll assume it's a typo).
The real problem is that you need a wrapper class to represent the data node of the json which should contain a list (or array) of ExPositions. The makerPositions and takerPositions should also become lists (or arrays) too. Add the following class and update the position properties of ExPositions:
public class Data
{
public List<ExPositions> data { get; set; }
}
// change positions to use a List too
public class ExPositions
{
...
public List<Positions> makerPositions { get; set; }
public List<Positions> takerPositions { get; set; }
}
Then you can deserialize using:
var result = JsonSerializer.Deserialize<Data>(json);
It's not clear where the ""total"": 2 property should be in your models (it's not clear in the json because of the issue I mentioned), you could add it to the Data class above (if it belongs there).
Online demo
Try with:
public class Positions
{
public string name { get; set; }
public string position { get; set; }
public string vwap { get; set; }
public string pnl { get; set; }
}
public class ExPositions
{
public string symbol { get; set; }
public string exposure { get; set; }
public string makerExposure { get; set; }
public string takerExposure { get; set; }
public string makerPnl { get; set; }
public string takerPnl { get; set; }
public Positions makerPositions { get; set; }
public Positions takerPositions { get; set; }
}
public class YourResult{
public ExPositions data { get; set; }
public int total { get; set; }
}
And then call:
var positions = JsonSerializer.Deserialize<YourResult>(json_string);
As haldo mentioned, there is a typo in your JSON. To quickly parse and validate your JSON data, you can use any online JSON parsers to validate your JSON data. I usually use the chrome extension JSON Viewer Pro.
Also, in the link that haldo provided to the .NET Fiddle for the demo, there is a trailing comma in JSON data which JSON deserializers might not ignore.
Here is the link to the edited demo that haldo provided.
Edited Demo
I am having a JSON response String that is a complex class, it looks like under mentioned :-
{
"data": [
{
"_id": "5d4d767270de4b0008c3cb10",
"CH_SYMBOL": "TITAN",
"CH_SERIES": "EQ",
"CH_MARKET_TYPE": "N",
"CH_TRADE_HIGH_PRICE": 250.3,
"CH_TRADE_LOW_PRICE": 246,
"CH_OPENING_PRICE": 247.6,
"CH_CLOSING_PRICE": 247.55,
"CH_LAST_TRADED_PRICE": 246.8,
"CH_PREVIOUS_CLS_PRICE": 246.1,
"CH_TOT_TRADED_QTY": 1502182,
"CH_TOT_TRADED_VAL": 372907497.3,
"CH_52WEEK_HIGH_PRICE": 4754.95,
"CH_52WEEK_LOW_PRICE": 154.2,
"CH_TOTAL_TRADES": 25225,
"CH_ISIN": "INE280A01028",
"CH_TIMESTAMP": "2012-03-13",
"TIMESTAMP": "2012-03-12T18:30:00.000Z",
"createdAt": "2019-08-09T13:34:42.045Z",
"updatedAt": "2019-08-09T13:34:42.045Z",
"__v": 0,
"VWAP": 248.24,
"mTIMESTAMP": "13-Mar-2012"
},
{
"_id": "5d4d76b46c032c0008a78a0a",
"CH_SYMBOL": "TITAN",
"CH_SERIES": "EQ",
"CH_MARKET_TYPE": "N",
"CH_TRADE_HIGH_PRICE": 247.9,
"CH_TRADE_LOW_PRICE": 241.2,
"CH_OPENING_PRICE": 244.3,
"CH_CLOSING_PRICE": 246.1,
"CH_LAST_TRADED_PRICE": 246.5,
"CH_PREVIOUS_CLS_PRICE": 239.95,
"CH_TOT_TRADED_QTY": 2602734,
"CH_TOT_TRADED_VAL": 636810839.3,
"CH_52WEEK_HIGH_PRICE": 4754.95,
"CH_52WEEK_LOW_PRICE": 154.2,
"CH_TOTAL_TRADES": 28433,
"CH_ISIN": "INE280A01028",
"CH_TIMESTAMP": "2012-03-12",
"TIMESTAMP": "2012-03-11T18:30:00.000Z",
"createdAt": "2019-08-09T13:35:48.154Z",
"updatedAt": "2019-08-09T13:35:48.154Z",
"__v": 0,
"VWAP": 244.67,
"mTIMESTAMP": "12-Mar-2012"
},
{
"_id": "5d4d7596d3f11300086653dc",
"CH_SYMBOL": "TITAN",
"CH_SERIES": "EQ",
"CH_MARKET_TYPE": "N",
"CH_TRADE_HIGH_PRICE": 241.4,
"CH_TRADE_LOW_PRICE": 231.2,
"CH_OPENING_PRICE": 234.1,
"CH_CLOSING_PRICE": 239.95,
"CH_LAST_TRADED_PRICE": 239.75,
"CH_PREVIOUS_CLS_PRICE": 231.4,
"CH_TOT_TRADED_QTY": 3178144,
"CH_TOT_TRADED_VAL": 755500633.45,
"CH_52WEEK_HIGH_PRICE": 4754.95,
"CH_52WEEK_LOW_PRICE": 154.2,
"CH_TOTAL_TRADES": 41314,
"CH_ISIN": "INE280A01028",
"CH_TIMESTAMP": "2012-03-09",
"TIMESTAMP": "2012-03-08T18:30:00.000Z",
"createdAt": "2019-08-09T13:31:02.992Z",
"updatedAt": "2019-08-09T13:31:02.992Z",
"__v": 0,
"VWAP": 237.72,
"mTIMESTAMP": "09-Mar-2012"
},
{
"_id": "5d4d76951063e700088d810e",
"CH_SYMBOL": "TITAN",
"CH_SERIES": "EQ",
"CH_MARKET_TYPE": "N",
"CH_TRADE_HIGH_PRICE": 234.4,
"CH_TRADE_LOW_PRICE": 227.4,
"CH_OPENING_PRICE": 229,
"CH_CLOSING_PRICE": 231.4,
"CH_LAST_TRADED_PRICE": 231.4,
"CH_PREVIOUS_CLS_PRICE": 230.8,
"CH_TOT_TRADED_QTY": 2133389,
"CH_TOT_TRADED_VAL": 492988507.9,
"CH_52WEEK_HIGH_PRICE": 4754.95,
"CH_52WEEK_LOW_PRICE": 154.2,
"CH_TOTAL_TRADES": 27837,
"CH_ISIN": "INE280A01028",
"CH_TIMESTAMP": "2012-03-07",
"TIMESTAMP": "2012-03-06T18:30:00.000Z",
"createdAt": "2019-08-09T13:35:17.664Z",
"updatedAt": "2019-08-09T13:35:17.664Z",
"__v": 0,
"VWAP": 231.08,
"mTIMESTAMP": "07-Mar-2012"
},
],
"meta": {
"series": [
"EQ"
],
"fromDate": "13-03-2010",
"toDate": "13-03-2012",
"symbols": [
"TITAN",
"TITAN"
]
}
}
Now I made my C# class structure to be like this
public class Data {
public string _id { get; set; }
public string CH_SYMBOL { get; set; }
public string CH_SERIES { get; set; }
public string CH_MARKET_TYPE { get; set; }
public double CH_TRADE_HIGH_PRICE { get; set; }
public int CH_TRADE_LOW_PRICE { get; set; }
public double CH_OPENING_PRICE { get; set; }
public double CH_CLOSING_PRICE { get; set; }
public double CH_LAST_TRADED_PRICE { get; set; }
public double CH_PREVIOUS_CLS_PRICE { get; set; }
public int CH_TOT_TRADED_QTY { get; set; }
public double CH_TOT_TRADED_VAL { get; set; }
public double CH_52WEEK_HIGH_PRICE { get; set; }
public double CH_52WEEK_LOW_PRICE { get; set; }
public int CH_TOTAL_TRADES { get; set; }
public string CH_ISIN { get; set; }
public string CH_TIMESTAMP { get; set; }
public DateTime TIMESTAMP { get; set; }
public DateTime createdAt { get; set; }
public DateTime updatedAt { get; set; }
public int __v { get; set; }
public double VWAP { get; set; }
public DateTime mTIMESTAMP { get; set; }
}
public class Meta {
public IList<string> series { get; set; }
public string fromDate { get; set; }
public string toDate { get; set; }
public IList<string> symbols { get; set; }
}
public class Application {
public IList<Data> data { get; set; }
public Meta meta { get; set; }
}
}
Now is it possible to just extract the public IList<Data> data { get; set; } and save it.
Instead of creating one instance to class Application, Just List <Data> could be extracted from the JSON string.
I am using JsonConvert.DeserialiseObejct(); to do that, any help would be of great help.
Thanks
Piyush Kumar
It took some time to figure out, Here the Model contains all the fields from JSON string and ActualModel is a class that I need.
model Model = JsonConvert.DeserializeObject<model>(whole_table_data_in_JSON, settings);
JObject partial = JObject.Parse(whole_table_data_in_JSON);
IList<JToken> results = partial["data"].Children().ToList();
IList<ActualModel> his = new List<ActualModel>();
foreach (JToken result in results)
{
// JToken.ToObject is a helper method that uses JsonSerializer internally
ActualModel temp = result.ToObject<ActualModel>();
his.Add(temp);
}
I have the following json
{
"android_play_store_link": "xyz",
"ios_app_store_link": "",
"sticker_packs": [
{
"identifier": "1",
"name": "abc",
"publisher": "Jane Doe",
"tray_image_file": "xyz.png",
"image_data_version":"1",
"avoid_cache":false,
"publisher_email":"",
"publisher_website": "",
"privacy_policy_website": "",
"license_agreement_website": "",
"stickers": [
{
"image_file": "abc.webp",
"emojis": ["☕","🙂"]
},
{
"image_file": "cdf.webp",
"emojis": ["😩","😰"]
},
{
"image_file": "efg.webp",
"emojis": ["☕","🙂"]
}
]
}
]
}
I have no acquaintance with json until now, How can i deserialize this ?
I know how to do the basic read and write code from persistent data path of unity. But how do i process this json ?
My main goal is as the player wins a level, a new key and value would be added to the "stickers" attribute, Also after some levels I want to add changes to the sticker packs attribute later.
Plus how will i modify the value of image data version in a specific sticker pack item ?
Thanks in advance
you can use Newtonsoft.Json library to deserialize and serialize. Find below the respective C# class.
public class Sticker
{
public string image_file { get; set; }
public IList<string> emojis { get; set; }
}
public class StickerPack
{
public string identifier { get; set; }
public string name { get; set; }
public string publisher { get; set; }
public string tray_image_file { get; set; }
public string image_data_version { get; set; }
public bool avoid_cache { get; set; }
public string publisher_email { get; set; }
public string publisher_website { get; set; }
public string privacy_policy_website { get; set; }
public string license_agreement_website { get; set; }
public IList<Sticker> stickers { get; set; }
}
public class Root
{
public string android_play_store_link { get; set; }
public string ios_app_store_link { get; set; }
public IList<StickerPack> sticker_packs { get; set; }
}
Code to Deserialize:
Root root = JsonConvert.DeserializeObject<Root>(json);
I have the following classes :
public class Solution
{
public string Id { get; set; }
public string ProjectName { get; set; }
public string CodeName { get; set; }
public string Description { get; set; }
public string Author { get; set; }
public string Createdate { get; set; }
public string LastEditedBy { get; set; }
public string Status { get; set; }
public string GoLive { get; set; }
public virtual List<State> States { get; set; }
}
public class State
{
public Solution Solution { get; set; }
public string SolutionId { get; set; }
public string StateId { get; set; }
public string StateValue { get; set; }
}
Where StateValue is raw json string.
When I want to deserialise this I get a json string with \r\n .
Ho to tell the json serializer to not escape that string and treat it as json because it is already json.
I want an output like this :
[
{
"id": "43c7f6d5-61dc-4c1c-8c76-e13878b7483f",
"projectName": "Test Request 2",
"codeName": "",
"description": "",
"author": "",
"createdate": "02/13/2019",
"lastEditedBy": "",
"status": "Pending",
"goLive": "02/13/2019",
"states": [
{
"id": "cd7363f8-752b-4eb2-aaa2-ef94d7685153",
"label": "Empty State",
"layerone": [
{
"StorageCloudPhysical_Custom3": "cc1",
"StorageCloudPhysical_WorkSpace": "ws for asset 2"
},
{
"StorageCloudPhysical_Custom3": "cc3",
"StorageCloudPhysical_WorkSpace": "ws for asset 4"
}
}
]
}
]
States in the json schema is the value of the operation Solution.States.Select(s => s.StateValue), which is something like List.
How can I achieve this please and thanks in advance.
EDITED:
What is your project type? Is it C# MVC?
First of all, you need to install the NewtonSoft library using Nuget, then, instantiate it on your controller.
Newtonsoft
using Newtonsoft.Json;
Now, you just "convert" your list, to a JsonList using serialize to do that.
var list = JsonConvert.SerializeObject<List<string>>(YorRawList).ToList();
The problem is, I receive a list of posts from facebook (page feed) which occasionally holds multiple comments in an array inside the post object. Only the first comment of the post gets parsed correctly. Somehow the second and later comments don't get parsed.
This is the JSON I'm going on about:
{
"data": [ //Root object
{ //Post object
"id": "153411918116843_304953306296036",
"from": {
"category": "Sports/recreation/activities",
"category_list": [
{
"id": "124887510918208",
"name": "Swimming Pool"
}
],
"name": "Twentebad",
"id": "153411918116843"
},
"link": "http://dlvr.it/5bBKPx",
"picture": "irrelevant",
"message": "Onderzoek renovatie Twentebad! http://dlvr.it/5bBKPx",
"created_time": "2014-05-07T09:44:18+0000",
"comments": { // Collective comments object
// Actual comments objects in array !!!!! ONLY FIRST GETS PARSED !!!!
"data": [
{ //Comment object
"id": "304953306296036_304959069628793",
"from": {
"id": "884483928243965",
"name": "Selena Suzan Valentino"
},
"message": "Twentepalace",
"can_remove": false,
"created_time": "2014-05-07T10:32:26+0000",
"like_count": 0,
"user_likes": false
},
{ Unparsed comment object
"id": "304953306296036_305126702945363",
"from": {
"id": "884483928243965",
"name": "Selena Suzan Valentino"
},
"message": "Na baantjes trekken vooral heerlijk...",
"can_remove": false,
"created_time": "2014-05-08T09:12:43+0000",
"like_count": 0,
"user_likes": false
},
{ //Unparsed comment object
"id": "304953306296036_305126622945371",
"from": {
"id": "884483928243965",
"name": "Selena Suzan Valentino"
},
"message": "Wil infrarood sauna weer terug komt...",
"can_remove": false,
"created_time": "2014-05-08T09:11:20+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "MQ==",
"before": "Mw=="
}
},
"summary": {
"order": "ranked",
"total_count": 3
}
}
}
]
}
I'm using JSON.NET to parse this json to a typed object list like this:
foreach (JToken facebookItem in data["data"])
{
JToken messageCheck = facebookItem.SelectToken("message", false); //Irrelevante post als er geen inhoud in zit (false = geen error melding indien null)
if (messageCheck != null)
{
itemsToAdd.Add(facebookItem.ToObject<FacebookItem>());
}
}
The FacebookItem class looks like this:
public class FacebookItem
{
public string id { get; set; }
public From from { get; set; }
public string link { get; set; }
public string picture { get; set; }
public string message { get; set; }
public string created_time { get; set; }
public Comments comments { get; set; }
public PostPaging paging { get; set; }
public class PostCategories
{
public string id { get; set; }
public string name { get; set; }
}
public class From
{
public string category { get; set; }
public List<PostCategories> category_list { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class CommentCategories
{
public string id { get; set; }
public string name { get; set; }
}
//Root of Comments ("data":[ "comments":{ [],{},{} } ])
public class Comments
{
public List<CommentData> data { get; set; } //SHOULD HOLD MORE THAN 1
public CommentPaging paging { get; set; }
public Summary summary { get; set; }
}
//Data gegevens van comments ("data":[ "comments":{ "data":[],{},{} } ])
public class CommentData
{
public string id { get; set; }
public CommentFrom from { get; set; }
public string message { get; set; }
public bool can_remove { get; set; }
public string created_time { get; set; }
public int like_count { get; set; }
public bool user_likes { get; set; }
}
//Data gegevens van ccommenter ("data":[ "comments":{ "data":[ "from":{} ],{},{} } ])
public class CommentFrom
{
public string id { get; set; }
public string name { get; set; }
public string category { get; set; }
public List<CommentCategories> category_list { get; set; }
}
//Paging gegevens van comments ("data":[ "comments":{ [],"paging":{},{} } ])
public class CommentPaging
{
public Cursors cursors { get; set; }
}
//Summary gegevens van comments ("data":[ "comments":{ [],{},"summary":{} } ])
public class Summary
{
public string order { get; set; }
public int total_count { get; set; }
}
public class Cursors
{
public string after { get; set; }
public string before { get; set; }
}
public class PostPaging
{
public string previous { get; set; }
public string next { get; set; }
}
}
Is there a Json.net expert out there that undertands why only the first comment gets parsed?
This is what the debugger show me:
I'll tell you where I live, please come and kill me...
I called the url from localstorage. I changed the url but changes aren't detected so it doesn't get overwritten.
So, why only one comment? I had the comments' limit set to 1 :(
Not as exiting as I hoped this would be.
Hopefully the info provided can help someone in the future.