1

I am using xamarin and c# and this is my first project using these. So kindly bear with me if this is a very basic question.

I have getting a JSON response from my server and I am trying to store these values in a class. I couldn't figure out how to do that in Csharp using JSON.Net

Here is my code :

OfferClass.cs

namespace TestApp_IOS_2
{
    public class OfferClass
    {
        public OfferClass ()
        {
        }

        private String title;

        public String getTitle ()
        {
            return title;
        }

        public void setTitle (String title)
        {
            this.title = title;
        }
    }
}

ViewDidLoad Method :

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();

    // Perform any additional setup after loading the view, typically from a nib.

    String jsonResponse = GetResponse ();

    Console.WriteLine ("Response : " + jsonResponse);
    this.textFieldResponse.Text = jsonResponse; 

    parseResponse (jsonResponse);
}

GetResponse Method :

public String GetResponse()
{

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            return reader.ReadToEnd();
        }
    }
    catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            Console.WriteLine ("error : "+errorText);
        }
        throw;
    }

}

}

ParseResponse Method :

public void parseResponse(String jsonResponse)
{
    OfferClass offer = new OfferClass ();

    //String output = Newtonsoft.Json.JsonConvert.SerializeObject (offer);
    //Console.WriteLine ("Output : " + output);

    offer = Newtonsoft.Json.JsonConvert.DeserializeObject<OfferClass> (jsonResponse);

    Console.WriteLine ("Offer Title : " + offer.getTitle());
}

Here is the exception that i am getting :

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TestApp_IOS_2.OfferClass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 3, position 2.

I understand what the error says, that Deserialize needs a JSON Object, but how to do that, is what is puzzling me.

EDIT :::

My JSON Example

{
"id":"138",
"coupon_title":"",
"coupon_image":null,
"owner_id":"181",
"title":"killer campaign",
"desc":"as",
"category_id":"49",
"active":"1",
"campaign_type":"Store Based",
"st_date":"2014-04-09 12:23:14",
"end_date":"2014-03-26 00:00:00",
"template_id":"0",
"campaign_template_title":"",
"template_title":"",
"campaign_template_id":null,
"campaign_offer":"reward",
"logo":"\/assets\/admin\/img\/thumb.jpg",
"status":"published",
"radius":"1.00",
"date_created":"0000-00-00 00:00:00",
"coupon_barcode":"",
"tinyurl":"http:\/\/is.gd\/gYthYp",
"location":"My Store",
"city":"Secunderabad",
"state_id":"3689",
"address_1":"Marredpally, Ranga Reddy, ",
"address_2":"Hyderabad",
"indoor_mall_location":"",
"zip":"500026",
"latitude":"17.4443717",
"longitude":"78.518472100",
"distance":0,
"link":"\/app\/rendersplash\/138\/cm\/23456789",
"reward_link":"\/app\/previewreward\/138\/23456789",
"return_to_offers_link":"\/app\/offers\/500026\/17.4435394\/78.5026527\/5\/json\/23456789"
}
2
  • What does your JSON look like? The error seems to be saying that you are trying to deserialize an array of objects into a single object. Additionally, OfferClass has no public properties. JSON.Net is not going to understand that setTitle() and getTitle() map to a "Title" property. Commented Apr 9, 2014 at 13:43
  • @Jason, edited my question. Please look at it Commented Apr 9, 2014 at 13:47

2 Answers 2

1

The OfferClass needs to be more C# friendly:

public class OfferClass
{
    public string Id { get; set; }
    public string Title { get; set; }
    // And so on... to match the JSON
}

Also, I think your JSON is actually an array. You have listed a single example, but I think it might be returning an array of similar items. You will need to Deserialize into an array or List<OfferClass>.

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

2 Comments

Ok.. will give it a try.. will get back to you
Thanks, used this... List<OfferClass> offers = Newtonsoft.Json.JsonConvert.DeserializeObject<List<OfferClass>> (jsonResponse);
1

Generate your class from your JSON using this tool

http://json2csharp.com/

Comments

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.