使用Xamarin for Android中的对象从Json对象创建对象列表 [英] Create list of objects from Json object with objects in xamarin for Android

查看:132
本文介绍了使用Xamarin for Android中的对象从Json对象创建对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON.net,并且尝试从JSON这样获取Expense对象的列表:

I`m using JSON.net and I'm trying to get a list of Expense objects from JSON like this:

{"ApplicationUser": null, "Currency": 1, "Description": "Moj pierwszy portfel", "Expenses": [{"Date": "2015-10-01T00:00:00", "Description": "Opis", "ExpenseType": {"Id": 1, "IsExpense": true, "Name": "Jedzenie"}, "ExpenseTypeId": 1, "Id": 1, "Name": "Biedronka", "Value": 40.00, "WalletId": 1}], "Id": 1, "Name": "Moj portfel", "Saldo": 100.12, "UserId": "f9b94a9a-44b3-4987-8711-6c1b73a5cb0e"}

api网址:http://homecalc.azurewebsites.net/api/wallets/2

我有从 JSON2C#

它们看起来像这样

public class ExpenseType
{
    public int Id { get; set; }
    public bool IsExpense { get; set; }
    public string Name { get; set; }
}

public class Expense
{
    public ExpenseType ExpenseType { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
    public double Value { get; set; }
    public string Description { get; set; }
    public string Date { get; set; }
    public int ExpenseTypeId { get; set; }
    public int WalletId { get; set; }
}

public class RootObject
{
    public List<Expense> Expenses { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
    public string UserId { get; set; }
    public double Saldo { get; set; }
    public int Currency { get; set; }
    public string Description { get; set; }
    public object ApplicationUser { get; set; }
}

像这样声明JSONValue:

Getting JSONValue is declarated like this:

private async Task<JsonValue> GetApi(string url)
    {
        HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(new Uri(url));
        request.ContentType = "application/json";
        request.Method = "GET";

        using (WebResponse response = await request.GetResponseAsync())
        {
            using (Stream stream = response.GetResponseStream())
            {
                JsonValue jsconDoc = await Task.Run(() => JsonObject.Load(stream));
                Console.Out.WriteLine("Response {0}", stream);

                return jsconDoc;
            }
        }
    }

我尝试过反序列化

var my_array = JsonConvert.DeserializeObject<List<RootObject>>(json);

并将其解析为jsonObject或jsonArray

and parsing it to jsonObject or jsonArray

var obj = JsonObject.Parse(json);

,但是它总是以中断应用程序结尾. 我也尝试使用json["Expenses"]仅获取一系列支出,但是当有两个支出时,它将全部作为一项支出返回.有人可以解释如何从中获取费用对象列表吗?

but it always ends with breaking the application. I also try to get only array of expenses using json["Expenses"] but it returns all as one expense when there are two expenses. Could someone explain how to get a list of expense objects from this?

我已经更改了代码,如下所示:

I've change code to look like this:

 private async Task<string> GetApi(string url)
    {
        HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(new Uri(url));
        request.ContentType = "application/json";
        request.Method = "GET";

        using (WebResponse response = await request.GetResponseAsync())
        {
            using (Stream stream = response.GetResponseStream())
            {
                JsonValue jsconDoc = await Task.Run(() => JsonObject.Load(stream));
                Console.Out.WriteLine("Response {0}", stream);
                StreamReader read = new StreamReader(stream,Encoding.UTF8);

                string json = read.ReadToEnd();

                return json;
            }
        }
    }

private void ParseAndDisplay(string json)
    {
        //TextView WalletName = FindViewById<TextView>(Resource.Id.PortfelName);
        //WalletName.Text = json["Name"];
        //Console.WriteLine("Exp {0}",json["Expenses"]);
        //JsonArray jsonnArray = new JsonArray(json["Expenses"]);
        try
        {
            var result = JsonConvert.DeserializeObject<RootObject>(json);
            Console.WriteLine("Nazwa: {0}",result.Name);
        }
        catch (Exception e)
        {
            Console.WriteLine("Błąd: {0}",e);
        }

    }

当我尝试运行此方法时,它将返回异常:

and when i try to run this methods it return an exception:

System.NullReferenceException: Object reference not set to an instance of an object

推荐答案

使用System.Net.Http.HttpClient和诸如Newtonsoft.Json或ServiceStack.Text之类的JSON库,不必花太多时间了解细节,这将相当简单.使用Newtonsoft.Json,您可能正在寻找这样的东西:

Without getting too far into details, using System.Net.Http.HttpClient and a JSON library like Newtonsoft.Json or ServiceStack.Text, this would be reasonably simple. Using Newtonsoft.Json, you might be looking for something like this:

using System.Net.Http;
using Newtonsoft.Json;

...

using (var client = new HttpClient())
{
    ...

    var response = await client.GetAsync(url);
    response.EnsureSuccessStatusCode();

    string json = await response.Content.ReadAsStringAsync();
    var result = JsonConvert.DeserializeObject<RootObject>(json);

    ...
}

这篇关于使用Xamarin for Android中的对象从Json对象创建对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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