hanali
hanali

Reputation: 227

convert an array to a string from a web service request C#

I have a php web service that I have tried to consume and parse data to my textbox in designer(I work on a windows 10 app store application),this is my code:

public sealed partial class MainPage : Page
    {
        public string uriString = "my URL";
        public MainPage()
        {
            this.InitializeComponent();
            Getdata();
        }

        private async void Getdata()
        {
            var http = new HttpClient();
            http.MaxResponseContentBufferSize = Int32.MaxValue;
            System.Collections.ArrayList response = new System.Collections.ArrayList(new string[] { await http.GetStringAsync(uriString) });
            var rootObject = JsonConvert.DeserializeObject<Sponsorises.RootObject>(response); //the error is here
            sponsorname.Text = rootObject.nom; //the name of my textBox
        }
        public class Sponsorises
     {

    internal class RootObject
    {
        public string nom { get; set; }
        public string tel { get; set; }
        public string photo { get; set; }
        public string sponsorise_adrs { get; set; }

    }
}

this is my json code:

 {
success: 1,
message: "sponsorise found!",
total: 1,
sponsorises: [
{
nom: "my third local",
tel: "88888888",
photo: "http://192.168.1.1/1446241709_ab_cart2_bleu2.png",
sponsorise_adrs: "the adress"
}
]
}

I am having problem in converting arraylist response to the string rootObject,have you please any idea thanks for help

Upvotes: 0

Views: 202

Answers (3)

Orkun Bekar
Orkun Bekar

Reputation: 1441

Add that to the beginning of each RootObject attribute:

[JsonProperty("fieldName")]

Upvotes: 1

Borophyll
Borophyll

Reputation: 1119

The issue is that JsonConvert.Deserialize() expects a string, not an array list.

This can be done by not casting your web response to ArrayList

var response = await http.GetStringAsync(uriString);
var rootObject = JsonConvert.DeserializeObject<RootObject>(response);

Upvotes: 1

Maxim Goncharuk
Maxim Goncharuk

Reputation: 1333

You may add another class for sponsorises:

internal class RootObject
{
    public string success { get; set; }
    public string message { get; set; }
    public string total { get; set; }
    public List<Sponsorise> sponsorises { get; set; }
}

class Sponsorise
{
    public string nom { get; set; }

    public string tel { get; set; }

    public string photo { get; set; }

    public string sponsorise_adrs { get; set; }
}

And deserialize like so:

var rootObject = JsonConvert.DeserializeObject<RootObject>(response); 
sponsorname.Text = rootObject.sponsorises[0].nom; 

Upvotes: 1

Related Questions