简体   繁体   English

从Web服务请求C#将数组转换为字符串

[英]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: 我有一个php web服务,我尝试使用它并将数据解析到设计器中的文本框(我在Windows 10应用商店应用程序上工作),这是我的代码:

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: 这是我的json代码:

 {
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 我在将arraylist响应转换为字符串rootObject时遇到问题,请给我任何帮助的想法

You may add another class for sponsorises : 您可以添加其他类别的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; 

The issue is that JsonConvert.Deserialize() expects a string, not an array list. 问题是JsonConvert.Deserialize()需要一个字符串,而不是数组列表。

This can be done by not casting your web response to ArrayList 这可以通过不将您的网络响应投射到ArrayList来完成

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

将其添加到每个RootObject属性的开头:

[JsonProperty("fieldName")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM