C# Parsing JSON String - c#

I have tried countless methods to Parse my JSON string (Steam Public Data), yet nothing seems to work. I just want to be able to extract values from the string. For Example, obtaining the value of personaname which would return SlothGod. I have JSON.NET installed in my project.
Here is my JSON:
{
"response": {
"players": [
{
"steamid": "76561198301407459",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "SlothGod",
"lastlogoff": 1508389707,
"commentpermission": 1,
"profileurl": "http://steamcommunity.com/id/sleuthgud/",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba.jpg",
"avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba_medium.jpg",
"avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba_full.jpg",
"personastate": 0,
"realname": "Josh",
"primaryclanid": "103582791460168790",
"timecreated": 1462086929,
"personastateflags": 0,
"loccountrycode": "AU",
"locstatecode": "QLD"
}
]
}
}
Main method suggested to me:
public class Details
{
public string personaname { get; set; }
}
private void GetSteamDetails()
{
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Details>(SteamDetailsJson);
SteamName = data.personaname;
}
This is placed before Page_Load(). I then call GetSteamDetails(); when I want to fetch the name.

After my question being down voted, I decided to not give up on this problem. After extensive research, trial and error, and YouTube tutorials which are the most helpful IMO. I found that the data was containing a JSON array, and yes I will admit, I was confused with this, but the answer was to simply treat it like a C# array and add [1] to the end of players.
Details details = new Details();
public class Details
{
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public string realname { get; set; }
public string personaname { get; set; }
public string steamid { get; set; }
}
private void GetSteamDetails()
{
var SteamDetails= JsonConvert.DeserializeObject<dynamic>(SteamDetailsJson);
avatar = SteamDetails.response.players[1].avatar.ToString();
personaname = SteamDetails.response.players[1].personaname.ToString();
}

Based on the JSON string you provided, you should have the following C# classes to support it, or to deserialize the JSON object values into: I used this link to generate the classes.
public class Player
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public int lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public int timecreated { get; set; }
public int personastateflags { get; set; }
public string loccountrycode { get; set; }
public string locstatecode { get; set; }
}
public class Response
{
public List<Player> players { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
Then, using Newtonsoft.Json, you can deserialize the JSON object into your C# classes as follow:
JsonConvert.DeserializeObject<RootObject>("yourJsonString");

You mention that Newtonsoft.Json already referenced in the project.
Use class to represent json data structure, then you can easy deserialize it.
You can use only properties you need in the class.
public class Player
{
public string personaname { get; set; }
}
var player = Newtonsoft.Json.JsonConvert.DeserializeObject<Player>(jsonString);
// use player.personaname
For updates question create classes which represent your data structure
public class Team
{
public List<Player> players { get; set; }
}
public class Response
{
public Team response { get; set; }
}

You can use http://json2csharp.com/ to generate a class automatically from a JSON string.

Related

Formatted Json Deserialize throws Exception

I was experiencing some to deserilize a json file until I realized the reason was that the file was formatted, prettified, beautified etc.
Using Newtonsoft.Json library and calling
JsonConvert.DeserializeObject<myObject>(mystring);
throws a JsonSerializationException:
{"Unexpected end when reading JSON. Path '', line 1, position 1."}
Then, when I repeated the operation, but with a minified, compacted, etc version of the same file it worked.
Is there a way to use this libray and deserialize data in both scenarios?
Thank you!
Your json is Valid, your model should be like this
public class Step
{
public int StepID { get; set; }
public string Description { get; set; }
public List<int> ShutMoves { get; set; }
public List<int> FeatIDs { get; set; }
public List<int> ExpSettings { get; set; }
}
public class Part
{
public int PartID { get; set; }
public string Description { get; set; }
public bool Moving { get; set; }
public List<int> FeatIDs { get; set; }
}
public class Feat
{
public int FeatID { get; set; }
public int CamID { get; set; }
public int CamFeatID { get; set; }
public int PartID { get; set; }
}
public class RootObject
{
public List<Step> Steps { get; set; }
public List<Part> Parts { get; set; }
public List<Feat> Feats { get; set; }
}
Small Example -
public void JsonDeserializeTesting() {
var testingModal = new TestingModal{Id = 1,Name = "Eminem",};
var serializeObject = JsonConvert.SerializeObject(testingModal);
var deserializeObject = JsonConvert.DeserializeObject<TestingModal>
(serializeObject);
Console.WriteLine($"{deserializeObject}");
}
public class TestingModal{
public long Id { get; set; }
public string Name { get; set; }
}
I hope this will give you abstract view of how to use Deserialize.
This was a mistake from my side. The string I was deserializing was obtained by using ReaLine(). So my code was parsing only the first line of the file.
ReadToEnd() from the stream or even File.ReadAllText fixes the issue.
Thank you for the help.

C# Objects to De-serialize JSON response from HERE Maps API

I'm just starting looking at REST API with HERE Maps.
I've got some experience of C# / .NET programming, but not very much with accessing REST APIs.
I have managed to successfully call the HERE Maps WebService and have retrieved the JSON data, but I'm trying to work out the best way to retrieve the specific information I need from this data.
I think I need to use Deserialisation, but this seems to require the creation of a suitable C# object to de-serialse into.
I was hoping that there is a repository somewhere where I could find these objects, rather than having to work them out from scratch, but can't find anything.
Any suggestions gratefully received.
Thanks,
Chris.
Json response:
{
"Response":{
"MetaInfo":{
"Timestamp":"2019-02-03T20:41:00.395+0000"
},
"View":[
{
"_type":"SearchResultsViewType",
"ViewId":0,
"Result":[
{
"Relevance":1.0,
"MatchLevel":"postalCode",
"MatchQuality":{
"PostalCode":1.0
},
"Location":{
"LocationId":"NT_CwZliV687TLYW4ZZKm4VNA",
"LocationType":"point",
"DisplayPosition":{
"Latitude":50.8082,
"Longitude":-0.39127
},
"NavigationPosition":[
{
"Latitude":50.8082,
"Longitude":-0.39127
}
],
"MapView":{
"TopLeft":{
"Latitude":50.82169,
"Longitude":-0.41262
},
"BottomRight":{
"Latitude":50.79471,
"Longitude":-0.36992
}
},
"Address":{
"Label":"BN11 3PQ, Worthing, England, United Kingdom",
"Country":"GBR",
"State":"England",
"County":"West Sussex",
"City":"Worthing",
"PostalCode":"BN11 3PQ",
"AdditionalData":[
{
"value":"United Kingdom",
"key":"CountryName"
},
{
"value":"England",
"key":"StateName"
},
{
"value":"West Sussex",
"key":"CountyName"
}
]
}
}
}
]
}
]
}
}
You can select JSON and paste C# classes in Visual Studio: Edit -> Paste Special -> Paste JSON as classes.
Then add NuGet package Newtonsoft.Json to solution and deserialize JSON to object, it will be looking as:
using Newtonsoft.Json;
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string json = "";//download json
Rootobject obj = JsonConvert.DeserializeObject<Rootobject>(json);
DateTime tt = obj.Response.MetaInfo.Timestamp;
}
}
public class Rootobject
{
public Response Response { get; set; }
}
public class Response
{
public Metainfo MetaInfo { get; set; }
public View[] View { get; set; }
}
public class Metainfo
{
public DateTime Timestamp { get; set; }
}
public class View
{
public string _type { get; set; }
public int ViewId { get; set; }
public Result[] Result { get; set; }
}
public class Result
{
public float Relevance { get; set; }
public string MatchLevel { get; set; }
public Matchquality MatchQuality { get; set; }
public Location Location { get; set; }
}
public class Matchquality
{
public float PostalCode { get; set; }
}
public class Location
{
public string LocationId { get; set; }
public string LocationType { get; set; }
public Displayposition DisplayPosition { get; set; }
public Navigationposition[] NavigationPosition { get; set; }
public Mapview MapView { get; set; }
public Address Address { get; set; }
}
public class Displayposition
{
public float Latitude { get; set; }
public float Longitude { get; set; }
}
public class Mapview
{
public Topleft TopLeft { get; set; }
public Bottomright BottomRight { get; set; }
}
public class Topleft
{
public float Latitude { get; set; }
public float Longitude { get; set; }
}
public class Bottomright
{
public float Latitude { get; set; }
public float Longitude { get; set; }
}
public class Address
{
public string Label { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string County { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public Additionaldata[] AdditionalData { get; set; }
}
public class Additionaldata
{
public string value { get; set; }
public string key { get; set; }
}
public class Navigationposition
{
public float Latitude { get; set; }
public float Longitude { get; set; }
}
}
Many thanks to all the comments. Your suggestions have been filed away for future reference.
In the end, because I only needed to access a couple of pieces of information, the whole converting to an object bitseemed a bit of overkill, so I got the result in XML instead, and used a couple of XML methods (GetElementsByTagName and ChildNodes) to extract the nodes I wanted.
But thanks again for your suggestions, and I'm sure I will use at least some of them in the future :)
Chris.

Custom C# object from JSON

I get the following JSON response.
[
{
"Issue": {
"ID": 80,
"Name": "Cold",
"Accuracy": 90,
"Icd": "J00",
"IcdName": "Acute nasopharyngitis [common cold]",
"ProfName": "Common cold",
"Ranking": 1
},
"Specialisation": [
{
"ID": 15,
"Name": "General practice",
"SpecialistID": 0
}
]
}
]
I tried to follow the instructions given here. But I can't seem to fit that solution here. And in the documentation is explained only the scenario where you already have the class predefined. Any help?
Presumptions
Your question is not even clear. What are you asking? I presume you are asking how to make a C# class from that JSON?
Solution
Firstly, the JSON is an array (if its top-level tags are [] its an array itself. If its top level is {} then its a single object.
So what you have is an array returned with one result inside of it.
Going to json2csharp and pasting your code gives this:
public class Issue
{
public int ID { get; set; }
public string Name { get; set; }
public int Accuracy { get; set; }
public string Icd { get; set; }
public string IcdName { get; set; }
public string ProfName { get; set; }
public int Ranking { get; set; }
}
public class Specialisation
{
public int ID { get; set; }
public string Name { get; set; }
public int SpecialistID { get; set; }
}
public class RootObject
{
public Issue Issue { get; set; }
public List<Specialisation> Specialisation { get; set; }
}
And you can see its created a RootObject almost indicating it is a single object, but you will need to deserialize this as a List<RootObject> not just RootObject.
So in C# that would be var result = JsonConvert.DeserializeObject<List<RootObject>>(theJsonString);
You should have a strongly typed c# class ready for your Json Response to be deserialized into... Json Utils has a generator to use, it came up with this:
public class Issue
{
[JsonProperty("ID")]
public int ID { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Accuracy")]
public int Accuracy { get; set; }
[JsonProperty("Icd")]
public string Icd { get; set; }
[JsonProperty("IcdName")]
public string IcdName { get; set; }
[JsonProperty("ProfName")]
public string ProfName { get; set; }
[JsonProperty("Ranking")]
public int Ranking { get; set; }
}
public class Specialisation
{
[JsonProperty("ID")]
public int ID { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("SpecialistID")]
public int SpecialistID { get; set; }
}
public class RootObject
{
[JsonProperty("Issue")]
public Issue Issue { get; set; }
[JsonProperty("Specialisation")]
public IList<Specialisation> Specialisation { get; set; }
}
Then use
RootObject jsonAsCSharpClass = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
I'm not 100% sure this class is good for you though, i have never some across a response where the root response is an array, without defining a root property first, see how it starts with "[" instead of { ??? You may want to also try
List<RootObject> jsonAsCSharpClass = JsonConvert.DeserializeObject<List<RootObject>>(jsonResponse);
Or wait for someone with more knowledge on the subject to come along...

Unable to deserialize JSON in c#

I am getting the below JSON in response from a REST API.
{
"data":{
"id":123,
"zoneid":"mydomain.com",
"parent_id":null,
"name":"jaz",
"content":"172.1 6.15.235",
"ttl":60,
"priority":null,
"type":"A",
"regions":[
"global"
],
"system_record":false,
"created_at":"2017-09-28T12:12:17Z",
"updated_at":"2017-09-28T12:12:17Z"
}
}
and trying to resolve using below code but that doesn't result in a correctly deserialized type.
var model = JsonConvert.DeserializeObject<ResponseModel>(response);
below is a class according the field I received in JSON response.
public class ResponseModel
{
public int id { get; set; }
public string zone_id { get; set; }
public int parent_id { get; set; }
public string name { get; set; }
public string content { get; set; }
public int ttl { get; set; }
public int priority { get; set; }
public string type { get; set; }
public string[] regions { get; set; }
public bool system_record { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
What is missing?
You're missing a wrapper class.
public class Wrapper
{
public ResponseModel data {get;set}
}
and then do:
var model = JsonConvert.DeserializeObject<Wrapper>(response).data;
to get the instance of your ResponseModel out the data property.
You can deduct this from your json:
{ "data":
{ "id":123, /*rest omitted */ }
}
The type that will receive this JSON needs to have a property named data. The suggested Wrapper class acts as that type.
According to json2csharp website, your model seems to be incorrect. Try this one :
public class ResponseModel
{
public int id { get; set; }
public string zoneid { get; set; }
public object parent_id { get; set; }
public string name { get; set; }
public string content { get; set; }
public int ttl { get; set; }
public object priority { get; set; }
public string type { get; set; }
public List<string> regions { get; set; }
public bool system_record { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class RootObject
{
public ResponseModel data { get; set; }
}
Here a cool trick you can do in Visual Studio 2015-2017 where it generates the the correct class if you just copy the JSON (ctrl + c).
You need to create a new class in visual studio and once inside the class go to Edit menu -> Paste special -> paste JSON As Classes.
Steps to generate json class
This will generate the C# object for that json for you and save you all the hassle :)
Your model does not match your response - it matches the data property. Simply wrap another object round it
public class ResponseData
{
public ResponseModel Data {get; set; {
}
and then
var model = JsonConvert.DeserializeObject<ResponseData>(response);

Deserializing this JSON response to C#

I have this specific JSON response that I am trying to deserialize without success. I am hoping someone can help me.
Here is the JSON response I get:
{
"num_locations": 1,
"locations": {
"98765": {
"street1": "123 Fake Street",
"street2": "",
"city": "Lawrence",
"state": "Kansas",
"postal_code": "66044",
"s_status": "20",
"system_state": "Off"
}
}
}
I used json2csharp http://json2csharp.com and got these recommended classes:
public class __invalid_type__98765
{
public string street1 { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string s_status { get; set; }
public string system_state { get; set; }
}
public class Locations
{
public __invalid_type__98765 __invalid_name__98765 { get; set; }
}
public class RootObject
{
public int num_locations { get; set; }
public Locations locations { get; set; }
}
But when I try to use it in my code:
var locationResponse = JsonConvert.DeserializeObject<RootObject>(response.Content);
What I get is (Watch):
locationResponse : {RestSharpConsoleApplication.Program.RootObject} : RestSharpConsoleApplication.Program.RootObject
locations : {RestSharpConsoleApplication.Program.Locations} : RestSharpConsoleApplication.Program.Locations
__invalid_name__98765 : null : RestSharpConsoleApplication.Program.__invalid_type__98765
num_locations : 1 : int
Obviously I am not creating (json2csharp) the right classes for the DeserializeObject, and sadly I have no control over the JSON response (vendor = SimpliSafe).
It is obvious the "98765" is meant to be a value (location number) but json2csharp makes it into this __invalid_type__98765 class and this is probably why it gets null.
Any idea how should the classes look for this particular JSON to be successfully deserialized?
Thanks!
Zachs
You should be able to do this with a dictionary:
public class MyData{
[JsonProperty("locations")]
public Dictionary<string, Location> Locations {get;set;}
}
public class Location
{
public string street1 { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string s_status { get; set; }
public string system_state { get; set; }
}
Do you have a non-Express version of Visual Studio? If so, copy the JSON to clipboard and then go to the Visual Studio menu: Edit >> Paste special >> Paste JSON as classes.
Using that gives:
public class Rootobject {
public int num_locations { get; set; }
public Locations locations { get; set; }
}
public class Locations {
public _98765 _98765 { get; set; }
}
public class _98765 {
public string street1 { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string s_status { get; set; }
public string system_state { get; set; }
}
That suggests your JSON structure is not quite right.
You can also specify the property name via an attribute to use to get around this:
public class RootObject
{
public int num_locations { get; set; }
public Locations locations { get; set; }
}
public class Locations
{
[JsonProperty("98765")]
public LocationInner Inner { get; set; }
}
public class LocationInner
{
public string street1 { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string s_status { get; set; }
public string system_state { get; set; }
}
...but it would really be better if the JSON were properly formatted such that the Locations was actually an array of location objects.

Categories