我是C#和Xamarin的初学者。我想用newtonsoft反序列化json数组? 这里是我的JSON文件:反序列化使用Newtonsoft和biding查看(MVVM)的JSON
{
"next": {
"$ref": "http://192.168.0.100:8080/ords/hr/employees/?page=1"
},
"items": [
{
"empno": 7369,
"ename": "SMITH",
"job": "CLERK",
"mgr": 7902,
"sal": 800,
"deptno": 20
},
{
"empno": 7934,
"ename": "MILLER",
"job": "CLERK",
"mgr": 7782,
"sal": 1300,
"deptno": 10
}
]
}
她是我的模型类:
public class RootObject
{
[JsonProperty("items")]
public Item[] Items { get; set; }
[JsonProperty("next")]
public Next Next { get; set; }
}
public class Next
{
[JsonProperty("$ref")]
public string Ref { get; set; }
}
public class Item
{
[JsonProperty("deptno")]
public long Deptno { get; set; }
[JsonProperty("empno")]
public long Empno { get; set; }
[JsonProperty("ename")]
public string Ename { get; set; }
[JsonProperty("job")]
public string Job { get; set; }
[JsonProperty("mgr")]
public long Mgr { get; set; }
[JsonProperty("sal")]
public long Sal { get; set; }
}
当我尝试反序列化到一个列表它抛出异常此行:
var data = JsonConvert.DeserializeObject<List<RootObject>>(json);
错误是:
其他信息:不能反序列化当前JSON对象(例如{“name”:“value”})类型为'System.Collections.Generic.List`1 [System.Object]',因为类型需要JSON数组(例如[1,2,3])才能正确地反序列化。
要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,以使其成为正常的.NET类型(例如,不是像整数这样的基本类型,不是像数组或List的集合类型),可以从JSON对象反序列化。 JsonObjectAttribute也可以添加到类型中,以强制它从JSON对象反序列化。
此代码desirialize JSON的,但我现在不retrive数据并填充类:
public class ApiServices {
public async Task<RootObject> GetRootObject()
{
var client = new HttpClient();
var url = string.Format("http://mysite/ords/hr/employees");
var response = await client.GetAsync(url);
var json = await response.Content.ReadAsStringAsync();
dynamic jsonDe = JsonConvert.DeserializeObject<RootObject>(json);
return jsonDe;
}
我已经创造了一些代码MainViewModel,但我不知道如何检索数据并插入类别项目:
public class MainViewModel
{
#region Properties
public ObservableCollection<RootItemViewModel> RootObjects { get; set; }
private ApiServices apiServices;
#endregion
#region Constructors
public MainViewModel()
{
//Create observable collections
RootObjects = new ObservableCollection<RootItemViewModel>();
//Instance services
apiServices = new ApiServices();
//Load Data
LoadData();
}
#endregion
#region Methods
private async void LoadData()
{
var emps = new RootObject();
emps = await apiServices.GetRootObject();
RootObjects.Clear();
foreach (var item in RootObjects)
{
RootObjects.Add(new RootItemViewModel
{
});
}
}
#endregion
}
}
类RootItemViewModel:
public class RootItemViewModel : RootObject
{
}
尝试JsonConvert.DeserializeObject(json);你的json顶层是一个对象而不是列表。 –
Cedar