gpt4 book ai didi

c# - 使用Newtonsoft和biding View(MVVM)反序列化JSON

转载 作者:行者123 更新时间:2023-12-03 10:42:43 26 4
gpt4 key购买 nike

我是C#和Xamarin的初学者。我正在尝试使用newtonsoft反序列化json数组吗?
这是我的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; }
}

当我尝试反序列化为List时,它将在此行上引发异常:

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

错误是:

Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.Object]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.


这段代码对Json进行了反序列化,但是我现在不检索数据并填充类:

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中创建了一些代码,但是我不知道如何检索数据并插入类Item:

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
{


}

最佳答案

1)您的Json响应显示,它仅包含RootObject类型的实例。

2) var data = JsonConvert.DeserializeObject<List<RootObject>>(json); 将不起作用,因为您尝试将RootObject转换为List<RootObject>。在您的错误响应中进行了描述。

3) dynamic jsonDe = JsonConvert.DeserializeObject<RootObject>(json);将起作用,因为在这里您将RootObject转换为RootObject。我还建议您使用“var”代替“dynamic”(请查看原因:dynamic vs var)

4)您的以下方法似乎存在错误:

private async void LoadData()
{
var emps = new RootObject();

emps = await apiServices.GetRootObject();

RootObjects.Clear();

//Mistake:
//You iterate through the previously cleared observable collection.
//it really should be "foreach (var item in emps.Items)"
foreach (var item in RootObjects)
{

RootObjects.Add(new RootItemViewModel
{


});
}
}

5)您似乎想用 Item上的 RootObject类型的数组喂可观察的集合:
public class RootObject
{
[JsonProperty("items")]
public Item[] Items { get; set; } //This property

[JsonProperty("next")]
public Next Next { get; set; }
}

因此,您实际上应该做的是像这样设置数据:
private async void GetRootObjectItems()
{
RootObject emps = await apiServices.GetRootObject(); //Get the root object
RootObjects.Clear(); //clear the list

foreach (var item in emps.Items) //Important, to get the data from the Array on the RootObject
{
///its a nice way to give your viewmodel a ctor signature that ensures a correct initialization
///public RootItemViewModel(Item item)
///{
/// this.Deptno = item.Deptno;
///}
RootObjects.Add(new RootItemViewModel(item));
}
}
}

6)RootItemViewModel继承 RootObject没有任何意义。您应该使它继承自 Item或使其拥有 Item类型的属性。

希望我能把事情弄清楚!

关于c# - 使用Newtonsoft和biding View(MVVM)反序列化JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47615299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com