I am attempting to get a value for a game from JSON, but there are multiple fields with the same name, so I was wondering whether there was a way in which I could just retrieve that individual value, here is the basic JSON structure:
"response": {
"game_count": 119,
"games": [
{
"appid": 3920,
"playtime_forever": 0
},
{
"appid": 4000,
"playtime_forever": 278
},
...
I need to somehow get a property by using an appID and then retrieving the playtime_forever key.
You can convert your JSON to class and then query:
class ResponseJSON
{
[JsonProperty("response")]
public Result Response { get; set; }
}
class Result
{
[JsonProperty("game_count")]
public string Count { get; set; }
[JsonProperty("games")]
public List<Game> Gmaes { get; set; }
}
class Game
{
[JsonProperty("appid")]
public string Id { get; set; }
[JsonProperty("playtime_forever")]
public string PlayTime { get; set; }
}
var resp = JsonConvert.DeserializeObject<ResponseJSON>(jsonstr);
And then you can iterate through your object with a for loop:
foreach(game in resp.Respone.Games) {
var playtime = game.PlayTime;
// do stuff here
}
Or you can use linq to query your games:
var selectiveGames = resp.Response.Games.Where(x=> x.PlayTime == 220).ToList();
You need to add newtonsoft dll from here to your project if you don't have it;
UPDATE: With original JSON the code above is working perfect.
Related
I've simplified the code (below) but I cannot figure out why the Result.Data property is not getting filled; it is always null. I've used jsonlint.com to validate the JSON (both this small sample and the full content). I built a separate project (using How to Deserialize a Complex JSON Object in C# .NET) and it successfully serializes the complex object listed there. But I cannot get this one to work and I'm stumped.
using System.Text.Json;
namespace JsonTest2;
public class Result
{
public string? Total { get; set; }
public string? Limit { get; set; }
public string? Start { get; set; }
protected List<Park>? Data { get; set; }
}
public class Park
{
public string? Id { get; set; }
}
internal class Program
{
var basepath = AppDomain.CurrentDomain.BaseDirectory;
var filepath = basepath.Split("\\bin")[0];
var filename = #$"{filepath}\NPS_response_small.json";
var jsonstr = File.ReadAllText(filename);
var response = JsonSerializer.Deserialize<Result>(jsonstr, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
This is the content of "NPS_response_small.json":
{
"total": "468",
"limit": "50",
"start": "0",
"data": [
{
"id": "77E0D7F0-1942-494A-ACE2-9004D2BDC59E"
},
{
"id": "6DA17C86-088E-4B4D-B862-7C1BD5CF236B"
},
{
"id": "E4C7784E-66A0-4D44-87D0-3E072F5FEF43"
}
]
}
you have to chanbe a protected attribute of property Data to a public. Json deserializer doesnt have any acces to this property
public List<Park>? Data { get; set; }
it would be much easier to use Newtonsoft.Json, but if you need protected for some reason, you can try this ( but I am not sure that it is a full replacement)
public List<Park>? Data { protected get; init ; }
[System.Text.Json.Serialization.JsonConstructor]
public Result (List<Park>? Data, string? Total, string? Limit, string? Start)
{
this.Data=Data;
this.Total=Total;
this.Limit=Limit;
this.Start=Start;
}
so I have a problem:
The code in JSON that you see there is a response that a webpage gives me. And the thing I want to do is really simple:
I just want to parse for example the "user_id", or "class".
I tried few things on stackoverflow that I found but no one works...
{
"data": {
"user": {
"class": "user",
"user_id": "81046537",
"etp_guid": "76411082-73ab-5aaa-9242-0bb752cf97a4",
},
},
}
Thanks !
There are many ways you can extract the user_id from the json. The most common way is to use Newtonsoft.Json package.
Assuming the json is stored as a string, you can call JObject.Parse().
var data = "{'data': {'user': {'class': 'user','user_id': '81046537','etp_guid': '76411082-73ab-5aaa-9242-0bb752cf97a4'} } }";
JObject jObject = JObject.Parse(data);
var userId = jObject["data"]["user"]["user_id"];
Console.WriteLine($"User id {userId}");
If your json is stored as a n object, then call JObject jObject = new JObject(data)
A preferred way is to serialise your json using business object. Simply create classes to match the json structure. e.g:
public class Response
{
public Data Data { get; set; }
}
public class Data
{
public User User { get; set; }
}
public class User
{
public string Class { get; set; }
public string User_id { get; set; }
public string Etp_guid { get; set; }
}
Then deserialize your object. e.g:
var response = JsonConvert.DeserializeObject<Response>(data);
Console.WriteLine($"User id {response.Data.User.User_id}");
I apologize in advance for the poor explanation of my problem.
I'm trying to read a JSON array that contains data.
Here's how the JSON looks:
{
"playerstats": {
"steamID": "76561198071680006",
"gameName": "GameName",
"achievements": [
{
"apiname": "AchievementName1",
"achieved": 0, <--- Data that I want to read
"unlocktime": 0
},
{
"apiname": "AchievementName2",
"achieved": 0, <--- Data that I want to read
"unlocktime": 0
},
{
"apiname": "AchievementName2",
"achieved": 1, <--- Data that I want to read
"unlocktime": 1477847680
}
]
,
"success": true
}
}
I'm trying to look at Newtonsoft.Json and how to use that yet I'm at a complete loss as to how to use this. Any help would be appreciated.
You can try JsonConvert.DeserializeObject to read json data.
Having
public class Rootobject
{
public Playerstats playerstats { get; set; }
}
public class Playerstats
{
public string steamID { get; set; }
public string gameName { get; set; }
public Achievement[] achievements { get; set; }
public bool success { get; set; }
}
public class Achievement
{
public string apiname { get; set; }
public int achieved { get; set; }
public int unlocktime { get; set; }
}
You can try this:
var filePath = path to your file;
var jsonData = System.IO.File.ReadAllText(filePath);
Rootobject objectValue =
Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(jsonData);
Note: you should remove <--- Data that I want to read parts from your json data because currently it is not a valid json format.
You may access to your desired properties like this
objectValue.playerstats.achievements[0].achieved //0
objectValue.playerstats.achievements[1].achieved //0
objectValue.playerstats.achievements[2].achieved //1
I'm trying to get a specific part of Json, but couldn't figure out how.
My json looks like:
[
{
"ResourceId":"1",
"ResourceText":"Hello",
"LanguageId":"1"
},
{
"ResourceId":"2",
"ResourceText":"World",
"LanguageId":"1"
}
.
.
.
]
So for example I want the part (changes according to pResourceId parameter, so what I'm trying to get changes everytime)
{
"ResourceId":"1",
"ResourceText":"Hello",
"LanguageId":"1"
}
But I couldn't get it. What I tried so far:
JObject data = JObject.Parse(jsonStringResources);
return data.Values().Where(x => x.Contains("ResourceId\" : \"" +pResourceId +"\"") ) as clsResource;
I would make a model for the format of your JSON:
class Model
{
public string ResourceId { get; set; }
public string ResourceText { get; set; }
public string LanguageId { get; set; }
}
And then you can do:
var models = JsonConvert.DeserializeObject<List<Model>>(jsonStringResources);
var matchingModel = models.Where(model => model.ResourceId == pResourceId).ToList().FirstOrDefault();
return JsonConvert.SerializeObject(matchingModel);
We deserialize the JSON into a list of our models. We then get the model where the ResourceId matches the pResourceId. Finally, we serialize the model again to get the JSON string.
When pResourceId == 1, the result is:
{
"ResourceId": "1",
"ResourceText": "Hello",
"LanguageId": "1"
}
If your json looks like that, you can deserialize it into object which would be:
public class JsonTestModel
{
public JsonTestModel()
{
}
public int ResourceId { get; set; }
public string ResourceText { get; set; }
public int LanguageId { get; set; }
}
and then you could search for it like this:
List<JsonTestModel> theListWithModels = JsonConvert.DeserializeObject<List<JsonTestModel>>(theJsonString);
var extractedModels = theListWithModels.Where(m => m.ResourceId == pResourceId);
I make a web request in Silverlight for windows phone. And this is the responce.
{"result": {
"account": null,
"checkInfo": null,
"command": null,
"shifts": [
{
"description": "17:45 - 17:55 work shift",
"id": 5459,
"venueId": 132
}]}}
I use Newtonsoft.Json.dll and my purpose is to catch the array - shifts.
JObject obj = JObject.Parse(StringShifts);
JArray sh = (JArray)obj["shifts"];
But every time sh value is null. What i'm i doing wrong? Thank you in advance.
The other way around is: (This is very helpful, if you are doing more operations like this in your project)
Create these classes in your project
public class Shift
{
public string description { get; set; }
public int id { get; set; }
public int venueId { get; set; }
}
public class Result
{
public object account { get; set; }
public object checkInfo { get; set; }
public object command { get; set; }
public List<Shift> shifts { get; set; }
}
public class RootObject
{
public Result result { get; set; }
}
And then in your code
var rootObject = JsonConvert.DeserializeObject<RootObject>(StringShifts);
foreach(var shift in rootObject.result.shifts)
{
Console.Write(shift.description);
}
This way you can have more control on your json response data. But L.B 's answer if it is one time process in your app.
var obj = (JObject)JsonConvert.DeserializeObject(json);
foreach (var shift in obj["result"]["shifts"])
{
Console.WriteLine((string)shift["description"]);
}
You are missing the root results node; this is how you should use it:
JArray sh = (JArray)obj["result"]["shifts"];
Also, do note that there is a missing } in the end of your JSON sample above!