Reputation:
I have generated a json file from Wen api which contain the Name, Shortext, Geoco-ordinates including latitude and longitude and Images. Now I want to Deserialize every object in the contrller cass so that I can show these in View. My json file look like this.
{
"poi":[
{
"Name": "Berlin",
"Shorttext": "Berlin is the capital of Germany and one of the 16 states of Germany.....",
"GeoCoordinates": {
"Longitude": 13.38333333,
"Latitude": 52.51666667
},
"Images": [
"BA5AB22B.jpg"
]
},
{
"Name": "munich",
"Shorttext": "Munich of the European Union with a population of above 1.5 million.....",
"GeoCoordinates": {
"Longitude": 11.56666667,
"Latitude": 48.13333333
},
"Images": [
"AA3CF664.jpg"
]
}
]
}
My Model class for this object is -
public class GeoCoordinates
{
public double Longitude { get; set; }
public double Latitude { get; set; }
}
public class Poi
{
public string Name { get; set; }
public string Shorttext { get; set; }
public GeoCoordinates GeoCoordinates { get; set; }
public List<string> Images { get; set; }
}
public class RootObject
{
public List<Poi> poi { get; set; }
}
I want to get every object from this class such as shorttext, latitude, longitude, images. How can I Deserialize using Json.net to get every single object.
I want my result in that way-
Name:
Shortext:
Latititude
Longitude:
Images:
Edited: Iam trying to get value in this way-
var ReadJson = System.IO.File.ReadAllText(@"E:\C# Learning\POI.json");
RootObject json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(ReadJson);
foreach (var item in json.poi)
{
Console.WriteLine("name: {0}, shorttext : {1}, Geo: {2} ,Image:{3}", item.Name, item.Shorttext,item.GeoCoordinates,item.Images);
}
Upvotes: 0
Views: 1338
Reputation: 1336
Try Deserialize in
List<Dictionary<string,string>>()
and then you can extract data as:
var data = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(ReadJson);
// you can simply pass your JSON string in place of ReadJson if you don't want to create a file
var val1 = data.Select(y => y["property name"]).Single();
var val2 = data.Select(y => y["property name"]).Single();
// and so on
Upvotes: 0
Reputation: 29522
Using Json.Net you can do something like this(it should also work with the JavaScriptSerializer
) :
var ReadJson = System.IO.File.ReadAllText(@"E:\C# Learning\POI.json");
RootObject json = JsonConvert.DeserializeObject<RootObject>(ReadJson);
foreach (var item in json.poi)
{
Console.WriteLine("name: {0}, shorttext : {1}, Latitutde: {2} , Latitutde: {3}, Image: {4}", item.Name, item.Shorttext, item.GeoCoordinates.Latitude, item.GeoCoordinates.Longitude, string.Join(" ", item.Images));
}
Anyway you should explain what is the problem... what are the expected output and the output you have for the moment...
Look at these articles:
Upvotes: 0