So I'm calling the LinkedIn API to get the profile data and it retrieves a JSON.
{
"firstName": "Cristian Viorel",
"headline": ".NET Developer",
"location": {
"country": {"code": "dk"},
"name": "Northern Region, Denmark"
},
"pictureUrls": {
"_total": 1,
"values": ["https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z..."]
}
}
I can use student.firstname, student.headline. How can I get the name of the location, or the value of the pictureUrl ?
Something like student.location.name or student.pictureUrls.values ?
Pretty easy with Json.Net. You first define your model:
public class Country
{
public string code { get; set; }
}
public class Location
{
public Country country { get; set; }
public string name { get; set; }
}
public class PictureUrls
{
public int _total { get; set; }
public List<string> values { get; set; }
}
public class JsonResult
{
public string firstName { get; set; }
public string headline { get; set; }
public Location location { get; set; }
public PictureUrls pictureUrls { get; set; }
}
Then you simply parse your Json data:
string json = #"{
'firstName': 'Cristian Viorel',
'headline': '.NET Developer',
'location': {
'country': {'code': 'dk'},
'name': 'Northern Region, Denmark'
},
'pictureUrls': {
'_total': 1,
'values': ['https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z...']
}
}";
JsonResult result = JsonConvert.DeserializeObject<JsonResult>(json);
Console.WriteLine(result.location.name);
foreach (var pictureUrl in result.pictureUrls.values)
Console.WriteLine(pictureUrl);
For the name yes, but for picture you need a for loop or if you just want the first item student.pictureUrls.values[0] (values seems to be an array).
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 know people asked and already got some answers very similar question before like this, but still, I couldn't figure it out about mine. I have a JSON file contains a multidimensional object, like below:
{
"Common": {
"Required": "Required Entry ",
"Photos": "Photos",
"Videos": "Videos",
"Register": "Register"
},
"Forms": {
"Form": "Forms",
"Name": "Name",
"Phone": "Phone",
"Email": "Email",
"Message": "Message"
},
"Sections": {
"Home": {
"EventDateTime": "",
"MainTitle": "",
"SubTitle": ""
},
"About": {},
"Venue": {},
"Schedule": {},
"Speakers": {},
"Sponsors": {},
"Price": {},
"Contact": {}
}
}
I would like to deserialize it into my view model (LanguagesViewModel) like this:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LanguagesViewModel
{
public Common Common { get; set; }
public Buttons Buttons { get; set; }
public Forms Forms { get; set; }
public Navbar Navbar { get; set; }
public Sections Sections { get; set; }
}
public class Common
{
public string Required { get; set; }
public string Photos { get; set; }
public string Videos { get; set; }
public string Register { get; set; }
}
public class Forms
{
public string Form { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Message { get; set; }
}
public class Sections
{
public Home Home { get; set; }
public About About { get; set; }
public Venue Venue { get; set; }
public Schedule Schedule { get; set; }
public Speakers Speakers { get; set; }
public Sponsors Sponsors { get; set; }
public Price Price { get; set; }
public Contact Contact { get; set; }
}
public class Home
{
public string EventDateTime { get; set; }
public string MainTitle { get; set; }
public string SubTitle { get; set; }
}
public class About
{
}
public class Venue
{
}
public class Schedule
{
}
public class Speakers
{
}
public class Sponsors
{
}
public class Price
{
}
public class Contact
{
}
}
Some of the snippet to do this:
using (StreamReader sr = new StreamReader(language_file_path))
{
string contents = sr.ReadToEnd();
items = JsonConvert.DeserializeObject<LanguagesViewModel>(contents);
}
Somehow, I only can get the first level of the objects, which is:
LanguagesViewModel{
Common:null,
Forms:null,
Sections:null
}
Not the second level, not the third level. Did I do something wrong or have I missed something? Very appreciated for any kind of help.
Thank you.
You can Use this static class
public static class JsonHelper
{
public static T ToObject<T>(this string content)
{
var obj = JObject.Parse(content).GetValue(typeof(T).Name);
if (obj == null)
throw new NullReferenceException();
else
return obj.ToObject<T>();
//This ToObject here is default method written in object
}
}
Usage
var mymodel= json.ToObject<Forms>();
Or create a JSON object and read it with magic strings.
//Creating your JSON object
JObject content = JObject.Parse(sr.ReadToEnd()//or your json);
//content["your object name"] let you access to you object
var common =(Common)content["Common"];
in multidimensional objects, you can access them like this.
//content["level1"]["level2"]["level3"] & ...
var sections= (Home)content["Sections"]["Home"];
Also this way may work but i prefer the way with magic strings.
dynamic jsonObject = new JObject.Parse(sr.ReadToEnd());
var common = jsonObject.Common;
You can find more in this link
I hope this Helps!
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();
I'm using Facebook graph API to search pages, https://graph.facebook.com/search?q=platform&type=page
Here is the response in json, i've included only one:
{
"data": [
{
"category": "Media/news/publishing",
"category_list": [
{
"id": "108366235907857",
"name": "Newspaper"
}
],
"name": "Arab News",
"id": "10250877124"
}
],
"paging": {
"next": "https://graph.facebook.com/search?limit=1&offset=1&type=page&q=media&__after_id=10250877124"
}
}
Now, here are my classes in C#:
public class CategoryList
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class DataRoot
{
[JsonProperty("category")]
public string Category { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("category_list")]
public CategoryList[] CategoryList { get; set; }
}
public class Paging
{
[JsonProperty("next")]
public string Next { get; set; }
}
public class FacebookPageResults
{
[JsonProperty("data")]
public DataRoot[] Data { get; set; }
[JsonProperty("paging")]
public Paging Paging { get; set; }
}
Here is the odd thing, when i try to deserialize it
FacebookPageResults response = new JavaScriptSerializer().Deserialize<FacebookPageResults>(res); , the CategoryList is always null, doesn't even fill up. I have tried with List CategoryList {get; set;} but the result is the same?
Any help or workaround about thi
If anyone is wondering, i found the solution:
FacebookPageResults response = JsonConvert.DeserializeObject(res);
This works
FacebookPageResults response = JsonConvert.DeserializeObject(res.ToString());
What is wrong with this code?
JSON
cities: [
{
city: {
id: 1,
name: "A.S.Peta",
status: "Active"
}
},..............
C# Code
public class Cities
{
public City[] cities;
}
public class City
{
public int id; //{ get; set; }
public string name; //{ get; set; }
public string status; //{ get; set; }
}
//De-Serialization
var jsSerialize = new JavaScriptSerializer();
var cities = jsSerialize.Deserialize<Cities>(result);
Not populating internal object City. but showing collection with all records. Any Idea?
The "inner" city in your json object is adding a nested object within the array.
Try this json code :
{
"cities": [
{
"id": 1,
"name": "A.S.Peta",
"status": "Active"
},
{
"id": 2,
"name": "Strasbourg",
"status": "Active"
}
]
}
If you need to stick to your originial json structure, you can try this c# code:
public class City2
{
public int id { get; set; }
public string name { get; set; }
public string status { get; set; }
}
public class City
{
public City2 city { get; set; }
}
public class RootObject
{
public List<City> cities { get; set; }
}
This code has been automatically generated by this very useful web tool: json2C#