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);
Related
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 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.
SO I have a Json array as following:
{[data, [{"name":"Micheal Jackson","pic_large":"https://scontent.x.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938","id":"10154729171332597"}
How can I serialize it with C# to parse it into objects and then pass it to the view.
EDIT:
{[data, [{"name":"Sayed Zubair Hashimi","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938","id":"10154729171332597"},{"name":"Junaid Walizada","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14055012_1760562554217155_4937121194048198140_n.jpg?oh=376b49c9d04c2676ebe3d853b122165e&oe=58EA033D","id":"1821833754756701"},{"name":"Mohib Akhondzada","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/s200x200/14264218_592094647641140_6351146344336469735_n.jpg?oh=a8a63893d71f76c45fa3d07389f1700a&oe=59147C84","id":"648198542030750"},{"name":"Za Beah","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15741112_359701871054520_6692094260041596196_n.jpg?oh=6d9a0e73f70145b821c79cbe738090a0&oe=58E5B5B5","id":"360411140983593"},{"name":"Baser Nader","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15094436_10153876544626432_1550234361821853528_n.jpg?oh=e197fa712b3180a20612ecdacb01747c&oe=58E54DEC","id":"10153975726331432"},{"name":"Abasin Deniz","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15698075_440749809647293_7905213567074684088_n.jpg?oh=aeb22664f458d75fc00638ca6fa4ecfc&oe=591F7BB3","id":"444098429312431"}]]}
EDIT2:
Here is how I retrieve above Json.
var appsecret_proof = access_token.GenerateAppSecretProof();
var fb = new FacebookClient(access_token);
dynamic myFeed = await fb.GetTaskAsync(
("me/feed?fields=likes{{name,pic_large}}")
.GraphAPICall(appsecret_proof));
The strings shown in your question are all invalid JSON. A properly formatted JSON might look like this:
{
"data": [{
"name": "Micheal Jackson",
"pic_large": "https://scontent.x.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938",
"id": "10154729171332597"
}]
}
Now if you want to map this to C# class that's pretty easy to do. Just define the models to reflect this structure:
public class Feed
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("pic_large")]
public string PicLarge { get; set; }
}
public class Result
{
[JsonProperty("data")]
public IList<Feed> Feeds { get; set; }
}
and then all that's left is to deserialize the JSON string using a JSON serializer such as Json.NET back to this object structure:
string json = ... the json string shown above
var result = JsonConvert.DeserializeObject<Result>(json);
foreach (var feed in result.Feeds)
{
Console.WriteLine(feed.Name);
}
first you need to create class with properties same as in json and then use the following code :
class obj
{
public string name {get ; set; }
public string pic_large {get ; set; }
public id {get ; set; }
}
using System.Web.Script.Serialization;
.
.
var obj = new JavaScriptSerializer().Deserialize<obj>(jsonString);
I am successfully deserializing a returned JSON array from a RESTful GET request into my C# plain old object model.
I am using the [JSONProperty foo] annotations to bind the JSON names to my model properties.
The JSON returned looks like this :
[{
"ProductCode": "0129923083091",
"Description": "DIESEL ",
"SalesLitres": 6058.7347,
"SalesValue": 6416.2000
},
{
"ProductCode": "0134039344902",
"Description": "UNLEADED ",
"SalesLitres": 3489.8111,
"SalesValue": 3695.7100
},
...
]
I would like to create something akin to a unique index field within my model which is synthesized based on the order of the appearance of the array items returned from JSON.
For reference, my current annotations (without the indexing property) looks like so :
namespace App8.Models
{
public class ReportRow
{
[JsonProperty("ProductCode")]
public string ProductCode { get; set; } = string.Empty;
[JsonProperty("Description")]
public string Description { get; set; } = string.Empty;
[JsonProperty("SalesLitres")]
public double SalesLitres { get; set; } = 0.0;
[JsonProperty("SalesValue")]
public double SalesValue { get; set; } = 0.0;
}
}
Is there an annotation for this provided by Newtonsoft JSON.net...
Or, is there some code which I can place within getter/setters to manufacture a primary key , in essence ?
Assuming
public class ReportRow {
public int Index { get; set; }
[JsonProperty("ProductCode")]
public string ProductCode { get; set; } = string.Empty;
[JsonProperty("Description")]
public string Description { get; set; } = string.Empty;
[JsonProperty("SalesLitres")]
public double SalesLitres { get; set; } = 0.0;
[JsonProperty("SalesValue")]
public double SalesValue { get; set; } = 0.0;
}
After deserializing the data
var data = JsonConvert.DeserializeObject<List<ReportRow>>(json);
You could use linq select to get indexes.
var indexedData = data.Select((item, index) => {
item.Index = index;
return item;
}).ToList();
Or, if index is not a property on model create a type on the fly with one.
var indexedData = data.Select((item, index) => new {
Index = index,
ReportRow = item
}).ToList();
I have a webservice that return a Json in this format :
[{
"Route0": {
"RouteID": "AAA",
"RouteDescription": "",
"ReturnCode": "0",
"ReturnError": ""
}
}, {
"Route1": {
"RouteID": "AABCLO",
"RouteDescription": "Antoine Abdo Bachaalani Close",
"ReturnCode": "0",
"ReturnError": ""
}
}]
I need to deserialize it:
I created 2 class:
public class PullRouteDetailsObjectChild
{
public string RouteID { get; set; }
public string RouteDescription { get; set; }
public string ReturnCode { get; set; }
public string ReturnError { get; set; }
}
public class PullRouteDetailsObject
{
public PullRouteDetailsObjectChild Route { get; set; }
}
and I am using this code to deserialize:
List<PullRouteDetailsObject> jsonRoutes =
JsonConvert.DeserializeObject<List<PullRouteDetailsObject>>(jsonresult);
I am able to get a list of 2 PullRouteDetailsObject wich is correct but the child object is always null.
I am sure that I am missing something but can't find what. I need to access child object
Thank you for your help.
You need to use this instead:
var jsonRoutes = JsonConvert.DeserializeObject<List<Dictionary<string, PullRouteDetailsObject>>>(jsonresult);
As you're getting a list of objects with a property which contains your 'PullRouteDetailsObject' (Route0, Route1).