序列化ListView数据以发送JSON POST [英] Serialize ListView Data to send JSON POST

查看:62
本文介绍了序列化ListView数据以发送JSON POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注以下问题

I am following this question ListView Get Multiple Entry Values to validate and send I need now to serialize data to send it to the server, I've got this far:

public class SurveyList
{
    public List<QuestionList> Questions { get; set; }
}

public class QuestionList
{
    public string QuestionLabel { get; set; }
    public string QuestionCode { get; set; }
}

public partial class SurveyPage : ContentPage
{
    private List<QuestionList> survey;

    public SurveyPage()
    {
        InitializeComponent();

        survey = new List<QuestionList>
        {
            new QuestionList { QuestionLabel = "Question 1?", QuestionCode = "01" },
            new QuestionList { QuestionLabel = "Question 2?", QuestionCode = "02" }
        };

        surveyList.ItemsSource = survey;
    }

    void Button_Clicked(object sender, System.EventArgs e)
    {
        HttpClient client = new HttpClient();

        client.BaseAddress = new Uri("http://myip");

        foreach (var getValues in survey)
        {
            Dictionary<string, string> listViewData = new Dictionary<string, string>()
            {
                { "Question", getValues.QuestionLabel },
                { "Answer", getValues.QuestionCode }
            };

            var listViewDataContent = new FormUrlEncodedContent(listViewData);

            var response = client.PostAsync("/api/GetData", listViewDataContent);
        }

    }
}

请帮助我正确获取所有要通过POST发送的数据.由于我获取的数据是动态的,因此不确定如何收集所有数据.

Please help me get all the data correctly to be sent via POST. Not sure how to collect all data, since the data I am getting is dynamic.

注意:那里显示的数据是静态的,但是应该从相同的API获取数据

Note: The data displayed there is static, but it should be getting the data from the same API

谢谢

添加我的Xaml代码

<ListView x:Name="surveyList"
      HasUnevenRows="true"
      SeparatorVisibility="Default" 
      BackgroundColor="White">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Padding="10" BackgroundColor="Purple">
                    <StackLayout Spacing="10" VerticalOptions="Start" HorizontalOptions="FillAndExpand" BackgroundColor="Olive">
                        <Label Text="{Binding QuestionLabel}" TextColor="Navy"/>
                        <Picker x:Name="QuestionPicker">
                            <Picker.Items>
                                <x:String>Yes</x:String>
                                <x:String>No</x:String>
                            </Picker.Items>
                        </Picker>
                    </StackLayout>
                    <StackLayout Spacing="20" VerticalOptions="End" HorizontalOptions="FillAndExpand" BackgroundColor="Maroon">
                    <Button x:Name="surveyButton"
                            Text="Enviar"
                            TextColor="White"
                            BackgroundColor="{StaticResource dpGreen}"
                            Clicked="Handle_Clicked"/>
                    </StackLayout>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.Footer>
        <Button x:Name="surveyButton"
            Text="Send"
            TextColor="White"
            BackgroundColor="Teal"
            Clicked="Handle_Clicked" />
    </ListView.Footer>
</ListView>

推荐答案

您无需手动编写Json,还有其他方法可以实现.

You don't have to manually compose your Json there are other ways to do it.

首先,将您的QuestionList对象修改为具有另一个名为Answer的字段,或者您更喜欢调用它.

First start by modifying your QuestionList object to have another field called Answer or however you prefer to call it.

public class QuestionList
{
    public string QuestionLabel { get; set; }
    public string QuestionCode { get; set; }
    public string Answer { get; set; }
}

此新属性将保留答案的值.

This new property will hold the value of the answer.

第二:将您的List<QuestionList>更改为ObservableCollection

Second: Change your List<QuestionList> for an ObservableCollection

此处:

private ObservableCollection<QuestionList> survey;

和此处

survey = new ObservableCollection<QuestionList>
{
    new QuestionList { QuestionLabel = "Question 1?", QuestionCode = "01" },
    new QuestionList { QuestionLabel = "Question 2?", QuestionCode = "02" }
};

稍微更改一下XAML.将Answer绑定到Picker SelectedItem.这是魔术"发生的地方.

Change a bit your XAML. Binding the Answer to the Picker SelectedItem. Here is where the "Magic" occurs.

<Picker x:Name="QuestionPicker" 
        SelectedItem="{Binding Answer, Mode=TwoWay}">
    <Picker.Items>
        <x:String>Yes</x:String>
        <x:String>No</x:String>
    </Picker.Items>
</Picker>

每次用户从Picker中选择一个值时,它将自动更新您设置为ItemsSource的列表的Answer属性.有关绑定的更多信息,请此处

Every time the user selects a value from the Picker it will be automatically update the Answer property of the List you set as the ItemsSource. More about Bindings here

现在,您只需更改Button Clicked事件,并使用此行代码即可完成Json. (首先,您需要安装 Newtonsoft Nugget )

Now you will just change the Button Clicked Event and with this line of code you will have a well done Json. (First you need to install Newtonsoft Nugget)

此处一个教程,展示了如何安装块块软件包(碰巧的是,他们使用相同的库作为示例,很幸运!).

Here a tutorial that shows how to install a nugget package (by coincidence they use this same library as example, lucky us!).

var json = JsonConvert.SerializeObject(survey);

上面将创建具有以下格式的json:

The above will create a json with the following format:

[
    {
        "QuestionLabel":"Question 1",
        "QuestionCode" : "01",
        "Answer":"No"
    },
    {
        "QuestionLabel":"Question 2",
        "QuestionCode" : "02",
        "Answer":"Yes"
    },
    {
        "QuestionLabel":"Question 3",
        "QuestionCode" : "03",
        "Answer":"Yes"
    },
    {
        "QuestionLabel":"Question 4",
        "QuestionCode" : "04",
        "Answer":"Yes"
    },
    {
        "QuestionLabel":"Question 5",
        "QuestionCode" : "05",
        "Answer":"No"
    }
]

如您所见,这表示一个QuestionList数组,您的服务器端点应该将其作为请求正文.为了清楚起见,我用随机值填充了Answer.

As you can see this represents an Array of QuestionList and your server Endpoint should be expecting this as the request body. I filled the Answer with random values for clarity.

整个Click事件代码看起来像

and the whole Click event code would look like

void Button_Clicked(object sender, System.EventArgs e)
{
    using(var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://myip");

        var json = JsonConvert.SerializeObject(survey);

        var listViewDataContent = new FormUrlEncodedContent(json);
        var response = client.PostAsync("/api/GetData", listViewDataContent);
    }
}

注意:请注意,我对初始化HttpClient的方式做了一些更改.是的,我知道文档存在,但是您正在创建新实例无论如何,每次单击按钮都不会,因为这不是问题的一部分,以免我们看不到它.

Note: Notice I change a bit the way you initialize your HttpClient. Yeah I know this document exists but you are creating a new instance anyway on every click of the button and since this is not part of the question lest say we did not see it.

注2:将值与服务器在json中期望的值匹配.这里重要的是向您展示了使用 Xamarin.Forms 绑定可以从ListView中获取值,并且还可以通过 Newtownsoft.Json 轻松地转换您的值.从 C#对象到 Json 的数据.有关此库的更多信息,请此处.

Note2: Match the values to what the server is expecting in the json. The important here was showing you that using the Xamarin.Forms Binding you could get the values out of the ListView and also that with Newtownsoft.Json you could easily convert your data from a C# Object to Json. More about this library here.

希望这会有所帮助.-

这篇关于序列化ListView数据以发送JSON POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆