How to deserializing JSON using JSON.NET (Getting null results) [duplicate] - c#

This question already has answers here:
How can I parse a JSON string that would cause illegal C# identifiers?
(3 answers)
Closed 8 years ago.
I am fairly new to C# / JSON and am working on a pet project to show summoner/game information from league of legends.
I am trying to get the summoner id for the requested summoner name.
Here is the JSON returned:
{"twopeas": {
"id": 42111241,
"name": "Twopeas",
"profileIconId": 549,
"revisionDate": 1404482602000,
"summonerLevel": 30
}}
Here is my summoner class:
public class Summoner
{
[JsonProperty(PropertyName = "id")]
public string ID { get; set; }
}
Here is the rest:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
var summonerInfo = JsonConvert.DeserializeObject<Summoner>(result);
MessageBox.Show(summonerInfo.ID);
summonerInfo.ID is null and I don't know why.
I'm sure there is something glaringly obvious that I am missing, but I'm at a loss I can't for the life of me figure it out.

Your ID is null because your JSON doesn't match the class you're deserializing into. In the JSON, the id property is not at the top level: it is contained within an object which is the value of a top-level property called twopeas (presumably representing the summoner name). Since this property name can vary depending on your query, you should deserialize into a Dictionary<string, Summoner> like this:
var summoners =
JsonConvert.DeserializeObject<Dictionary<string, Summoner>>(result);
MessageBox.Show(summoners.Values.First().ID);

Related

Retrieve a value among several json fields if this one is equal to another value of this json [duplicate]

This question already has answers here:
Get values from dynamic JSON properties C#
(2 answers)
Closed 2 years ago.
I'm sorry if I'm asking a trivial question but I'm stuck so I'm asking for your help.
I currently have a dynamic json that I receive, and I would like that according to the value of the phone the corresponding field is retrieved.
For exemple in my foreach(var item in jsonResult),
if item["Phone"].Value = "PSTN"( or "UIFN", "TS", "RS", "TF" ) then I would like to retrieve the json field which corresponds with its value, in this case it would be "PSTN".
If anyone has an idea how I can make this happen.
Thank you in advance for your answers and your help.
I believe this post can help you.
Try this code:
JObject jObject = JObject.Parse(jsonResult);
var result = (JObject)jObject["put here your top node level"];
foreach(JProperty prop in result.Properties())
{
if (prop.Name == item["Phone"].Value)
{
var values = jObject["put here your top node level"][prop.Name].Values<string>(item["Phone"].Value);
// do something
}
}
You could do it like this. thang.json is a file with json you provided.
var json = File.ReadAllText("thang.json");
var deserialized = JsonConvert.DeserializeObject<dynamic>(json);
if (new[] {"PSTN", "UIFN", "TS", "RS", "TF"}.Contains((string) deserialized.Phone))
{
Console.WriteLine(deserialized[(string)deserialized.Phone]);
}

C# Select From Json List Using Where Clause [duplicate]

This question already has answers here:
Find an item in a list by LINQ
(14 answers)
Closed 4 years ago.
I have a json list and I have a type named post. I want to use it for search.
I want to get a list or one object with a query. Is that possible ?
Example part of json
{
"Post": [
{
"id":"22",
"text":"Dream Big",
"img":"a2ca3cf9-664e-4d92-80f1-df20e971b7c0.jpg",
"catid":"12",
"meta_title":"Dream Big Design",
"content":"some text",
"user_id":"5556",
}
{
"id":"24",
"text":"Handmade Resin",
"img":"423233-971b7c0.jpg",
"catid":"7",
"meta_title":"Handmade Resin",
"content":"some text",
"user_id":"1256",
}
]
}
I want to select id = 23 or name like 'handmade'.
I tried with this code but it did not work
string json = System.IO.File.ReadAllText(path + "output.json");
var serializer = new JavaScriptSerializer();
Post post = JsonConvert.DeserializeObject<Post>(json);
you can use JObject in the C# that can parse the Json object and then you can fire your Select query.
JObject jObject = JObject.Parse(your Json object in string);

Is it possible to add fields with invalid characters to a .net AnonymousType?

I'm trying to send a JSON message to facebook that they call a game.achievement but I wanted to create the object using an AnonymousType before Posting. The problem is one of the fields is "game:points" (with the colon). As you can see I've used the # prefix for the object field but it doesn't work for the game:points field. It gets underlined in red and won't compile.
var paramsJson = new
{
privacy = new { value = "ALL_FRIENDS" },
#object = new
{
app_id = "my app id",
type = "game.achievement",
title = "Test",
#"game:points" = 100,
description = "Test",
image = "img.png"
}
};
I've tried many varieties of #, double quotes etc. Is it possible or do I need to just use a StringBuilder for this?
Why don't you just use a dictionary?
var postData = new Dictionary<string, object>
{
{"game:points", 100}
}
Presumably you're going to have to serialize your object to Post it regardless of how it's constructed. Serializing this to JSON would result in the same structure. Alternatively, just do as other's have suggested and create a class for your payload. You can then use Newtonsoft to indicate alternative names for serialization.
public class GameAchievement
{
[JsonProperty("game:points")]
public int Points {get; set;}
}

Getting null values when deserializing a list using RestSharp

I am new to C# and to RestSharp.
I am writing a small program to retrieve a list of records via REST. I have been able to retrieve one record. Now I need to get a list of records, and here I have a problem.
The response I get using SoapUI looks like this:
{
"#count": 2,
"#start": 1,
"#totalcount": 2,
"Messages": [],
"ResourceName": "email",
"ReturnCode": 0,
"content": [
{"email": {"evsysseq": "0000000000000262"}},
{"email": {"evsysseq": "0000000000000263"}}
]
}
My code looks like this:
class EmailID
{
public string Evsysseq { get; set; }
}
var client = new RestClient("xxxxx");
client.Authenticator = new HttpBasicAuthenticator("xxx", "xxx");
string queryParm = HttpUtility.UrlEncode("evsysseq>\"0000000000000261\"");
var request = new RestRequest("xxxx?query="+ queryParm, Method.GET);
request.RootElement = "content";
var queryResult = client.Execute<List<EmailID>>(request).Data;
Running it does not result in errors, and I can see on the queryResult object that it does contain two records. But, Evsysseq is null on both, and that is my problem. I am not sure what to tweak to get it right.
You are getting null values because the JSON you are deserializing does not match the class structure you are deserializing into. You are telling RestSharp to deserialize the content array into a List<EmailID>, but the JSON really represents a list of objects that contain EmailID objects. And so you need another class:
class EmailObj
{
public EmailID Email { get; set; }
}
Then deserialize like this and you should get the data:
var queryResult = client.Execute<List<EmailObj>>(request).Data;
If you want to, you can then use LINQ to get the List<EmailID> that you originally wanted like this:
var emailIds = queryResult.Select(eo => eo.Email).ToList();
HTH

How do I get properties in the array in this JSON string?

In the JSON string below, how do I access the values of the "at" and "current_value" properties within the "datastreams" array ?
In this example, there is only one datastream but in reality there could be many. I need to access the datastream by "id" property. Once I figure out this issue, I plan to use a where clause with the id == to the id of the desired datastream.
I tried using the approach discussed here, under "JSON in Windows 8 – A Simpler Approach" but it's not working.
In this code, json contains the JSON returned from the service I'm calling. prop is populated with a JsonArray. current results in an exception with an inner message of "JSON value not found"
var json = JsonObject.Parse(responseBodyAsText);
var prop = json.GetNamedArray("datastreams");
var current = from p in prop
select new
{
datastream = p.GetObject().GetNamedString("datastreams"),
datetime = p.GetObject().GetNamedString("at"),
value = p.GetObject().GetNamedString("current_value")
};
Here is the JSON string:
{
"title":"X",
"status":"X",
"creator":"X",
"datastreams":
[
{
"at":"x",
"max_value":"X",
"current_value":"X",
"id":"X",
"min_value":"X"
}
],
"location":{"exposure":"x","domain":"x","disposition":"x","lat":X,"lon":-X},
"created":"X",
"tags":["X"],
"feed":"X",
"private":"X",
"id":X,
"description":"X",
"version":"X",
"updated":"X"
}
datastream = p.GetObject().GetNamedString("datastreams")
The code above should return an array of objects. You'll need to loop through the array of objects to check the value of each object's "at" and "current_value" properties.
datastream return an array as you can notice by [ ] so:
datetime = datastream[0].at
value = datastream[0].current_value

Categories