问题
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 url: http://homecalc.azurewebsites.net/api/wallets/2
I have classes builded from JSON2C#
and they looks like this
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; }
}
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;
}
}
}
I've tried deserialization
var my_array = JsonConvert.DeserializeObject<List<RootObject>>(json);
and parsing it to jsonObject or jsonArray
var obj = JsonObject.Parse(json);
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
回答1:
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);
...
}
来源:https://stackoverflow.com/questions/34602909/create-list-of-objects-from-json-object-with-objects-in-xamarin-for-android