使用xamarin for Android中的对象从Json对象创建对象列表

时间:2016-01-05 01:41:18

标签: android json xamarin json.net deserialization

我正在使用JSON.net,我正试图从JSON获取一个Expense对象列表,如下所示:

{"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 url: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的声明如下:

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

var obj = JsonObject.Parse(json);

但它总是以破坏应用程序结束。 我也尝试使用json["Expenses"]获得一系列费用,但是当有两个费用时,它会将所有费用作为一项费用返回。有人可以解释如何从中获取费用对象列表吗?

我将代码更改为:

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

    }

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

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

1 个答案:

答案 0 :(得分:0)

使用System.Net.Http.HttpClient和像Newtonsoft.Json或ServiceStack.Text这样的JSON库,没有太深入细节,这将相当简单。使用Newtonsoft.Json,您可能正在寻找类似的东西:

length