簡體   English   中英

使用JSON.net解析JSON字符串

[英]Use JSON.net to parse json string

我正在使用xamarin和c#,這是我使用這些工具的第一個項目。 如果這是一個非常基本的問題,請多多包涵。

我從服務器收到JSON響應,並且試圖將這些值存儲在類中。 我不知道如何使用JSON.Net在Csharp中做到這一點

這是我的代碼:

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方法:

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方法:

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方法:

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());
}

這是我得到的例外:

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.

我理解錯誤說明,反序列化需要一個JSON對象,但是如何做到這一點卻讓我感到困惑。

編輯:::

我的JSON范例

{
"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"
}

使用此工具從JSON生成類

http://json2csharp.com/

OfferClass需要更加C#友好:

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

另外,我認為您的JSON實際上是一個數組。 您只列出了一個示例,但我認為它可能會返回一組相似的項目。 您將需要反序列化為數組或List<OfferClass>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM