1

I am trying to Deserilize json data from wikipedia api. I want to get only the Image information and then serilize again for my own formatted JSON Data. But the problem in my code is that it shows only the last data from the list, Not the entire data.The foreach loop is not working.

My Code to Deserialize and serialize json object is look like this-

[SwaggerResponse(HttpStatusCode.OK, "A", typeof(PoiImageAnswer))]
    [SwaggerResponse(HttpStatusCode.BadRequest, "Empty Answer", typeof(ModelStateDictionary))]
    [SwaggerResponse(HttpStatusCode.InternalServerError, "No Response")]
    [HttpPost]
    [ActionName("Image")]
    public IHttpActionResult Image([FromBody] PoiImageRequest request)
    {
        var result = new PoiImageAnswer {TransactionID = request.TransactionID};



       using (WebClient client = new WebClient())
       {
        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<PoiImageAnswer> poi = new List<PoiImageAnswer>();

        foreach (var page in json.query.pages)
          {

              try
               {

                var Img= page.thumbnail.source;
                result.Title = page.title;
                result.Height = page.thumbnail.height;
                result.Width = page.thumbnail.width;
                result.ImageData = string.Format("{0:X}.jpg", page.thumbnail.source.GetHashCode());
                result.TransactionID = request.TransactionID;
            }
            catch (Exception)
            {

            }

         }       
           return Ok(result);
         }

       }
    }

My C# class for json object is as below for understanding the code,

 public class PoiImageAnswer
 {
    public string ImageID { set; get; }
    public string Title { set; get; }
    public int Width { set; get; }
    public int Height { set; get; }
    public string ImageData { set; get; }
    public long TransactionID { set; get; }
 }


 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 getting output like this which is the last object from the list-

{
"ImageID": null,
"Title": "1976 Conference of Communist and Workers Parties of Europe",
 "Width": 243,
 "Height": 400,
 "ImageData": "53E5DCF3.jpg",
 "TransactionID": 0

}

5
  • It is because result variable of type PoiImageAnswer is single object and not collection. If you need all items from list then you need collection where you will store formatted json object and then this collection you need to send as result. Commented Mar 9, 2016 at 17:18
  • @PankajKapare, Could you please explain me how can I do that. I am very new in this case. Thank you. Commented Mar 9, 2016 at 17:19
  • Harry, you need to brush up on Collections in .NET; the System.Collections.Generic namespace in particular in order to deal with lists. Good luck! Commented Mar 9, 2016 at 17:21
  • @Moby'sStuntDouble. Could you please explain a little bit more. Actually I am very new handling this case. Commented Mar 9, 2016 at 17:23
  • There you go, Harry. I gave you an answer with explanations of what I was speaking about above. Commented Mar 9, 2016 at 17:38

2 Answers 2

1

You need code something like below. Note: I haven't tested it but it should work.

public IHttpActionResult Image([FromBody] PoiImageRequest request)
    {            
        var resultList = new List<PoiImageAnswer>();

        using (WebClient client = new WebClient())
        {
            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);

            foreach (var page in json.query.pages)
            {

                try
                {
                    var result = new PoiImageAnswer();
                    var Img = page.thumbnail.source;
                    result.Title = page.title;
                    result.Height = page.thumbnail.height;
                    result.Width = page.thumbnail.width;
                    result.ImageData = string.Format("{0:X}.jpg", page.thumbnail.source.GetHashCode());
                    result.TransactionID = request.TransactionID;
                    resultList.Add(result);
                }
                catch (Exception)
                {

                }

            }
            return Ok(resultList);
        }

    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thnk you very much. your code is working. But I have a small question that how can I set then var result = new PoiImageAnswer {TransactionID = request.TransactionID}; because in your code you wrote var resultList = new List<PoiImageAnswer>();
result.TransactionID = request.TransactionID; This line is already updating TransactionId so you don't need to initialize it while declaring it.
Thank you very much for explanation
1

You need to compile and send back a List. You are doing a foreach loop, but not compiling the list and sending it to the View.

Your code should look something like this (untested):

[SwaggerResponse(HttpStatusCode.OK, "A", typeof(List<PoiImageAnswer>))]
[SwaggerResponse(HttpStatusCode.BadRequest, "Empty Answer", typeof(ModelStateDictionary))]
[SwaggerResponse(HttpStatusCode.InternalServerError, "No Response")]
[HttpPost]
[ActionName("Image")]
public IHttpActionResult Image([FromBody] PoiImageRequest request)
{
    using (WebClient client = new WebClient())
    {
        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<PoiImageAnswer> poi = new List<PoiImageAnswer>();
        foreach (var page in json.query.pages)
        {
            try
            {
                poi.Add(new PoiImageAnswer {
                    TransactionID = request.TransactionID,
                    Title = page.title,
                    Height = page.thumbnail.height,
                    Width = page.thumbnail.width,
                    ImageData = string.Format("{0:X}.jpg", page.thumbnail.source.GetHashCode())
                });
            }
            catch (Exception)
            {

            }
        }       
        return Ok(poi);
    }
}

N.B.

  1. The change in your SwaggerResponse type.
  2. The poi.Add() in your try statement.
  3. The return of poi - your answer list, not result.
  4. You will need to add a using at the top of the controller for System.Collections.Generic if there isn't already one there.

Good luck with your app!

3 Comments

Thank you very much for explanation: Now I got a result. But I have a small question what should I do in this line var result = new PoiImageAnswer {TransactionID = request.TransactionID};
It's already being set, harry, look in the try. You don't need that original line at the top.
Thanks a lot. Yes now I understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.