Search code examples
c#serializationjson.netjson-deserializationjsonserializer

JSON Deserialization to get some particular objects and Serialize with new Json format using C#


For my project I need to Deserialize a long JSON data from Wikipedia. Then I need to get some particular information like Title, Extract, Thumbnail Source, Co-ordinates from that JSON. After getting all these data I need to serialize it again in a new formatted JSON.Hence I wrote a code for this.But having lot of problem with this code. I gave a description of every error beside my coding.

I am using this api from wikipedia

https://en.wikipedia.org/w/api.php?format=json&action=query&redirects=1&generator=geosearch&prop=extracts|coordinates|pageimages&ggslimit=20&ggsradius=1000&ggscoord=52.5243700|13.4105300&&formatversion=2&exintro=1&explaintext=1&exlimit=20&coprop=type|dim|globe&colimit=20&piprop=thumbnail&pithumbsize=400&pilimit=20

My C# object for this json is as below-

public class Coordinate
{
    public double lat { get; set; }
    public double lon { get; set; }
    public string primary { get; set; }
    public string type { get; set; }
    public string dim { get; set; }
    public string globe { get; set; }
}

public class Thumbnail
{
    public string source { get; set; }
    public int width { get; set; }
    public int height { get; set; }
}

public class Page
{
    public int pageid { get; set; }
    public int ns { get; set; }
    public string title { get; set; }
    public string extract { get; set; }
    public List<Coordinate> coordinates { get; set; }
    public Thumbnail thumbnail { get; set; }
}

public class Query
{
    public List<Page> pages { get; set; }
}

public class RootObject
{
    public bool batchcomplete { get; set; }
    public Query query { get; set; }
}

Now I create a C# Class to serialize my resulted Json object. I want my final Json in this way-

public class Poi
{  
    public string Title { set; get; }
    public string Description { set; get; }
    public List<PoiImage> Images { set; get; }
    public string OpeningHours { set; get; }
    public double AirDistanceInKm { set; get; }
    public double Lon { set; get; }
    public double Lat { set; get; }
}

public class PoiImage
{
    public string ImageID { set; get; }
}

I am using this code to Deserialize and Seralize JSON objects. But having lot of problems which I have mentioned beside code.

Edited Code

using (WebClient client = new WebClient())
{
    try
    {              
        var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&redirects=1&generator=geosearch&prop=extracts|coordinates|pageimages&ggslimit=20&ggsradius=1000&ggscoord=52.5243700|13.4105300&&formatversion=2&exintro=1&explaintext=1&exlimit=20&coprop=type|dim|globe&colimit=20&piprop=thumbnail&pithumbsize=400&pilimit=20"); 
        var json = JsonConvert.DeserializeObject<RootObject>(response);

        List<Poi> poi = new List<Poi>();

        foreach (var page in json.query.pages) 
        {
            Poi obj = new Poi();
            obj.Title = page.title;
            obj.Description =page.extract ;

            var Image = new PoiImage();
            var ImgfirstKey = page.thumbnail.source;
            Image.ImageID = string.Format("{0:X}.jpg", ImgfirstKey.GetHashCode());

            obj.Images = new List<PoiImage> {Image};

            obj.Lat = page.coordinates.First().lat;
            obj.Lon = page.coordinates.First().lon;

            poi.Add(obj);          
        }

        JsonSerializerSettings serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented };
        string result= Newtonsoft.Json.JsonConvert.SerializeObject(poi, serializerSettings);
        Console.WriteLine(result);
    }
    catch(Exception)
    {
    }
}

Solution

  • Just move the serialize code outside of the foreach and serialize the list<poi>

    foreach (page in rootObject.Query.Pages){
    
    //do the magic
    //then
    poi.add(obj)
    }
    
    
    
    JsonSerializerSettings serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented };
    Newtonsoft.Json.JsonConvert.SerializeObject(poi, serializerSettings);