在UWP中将json对象转换为XML

时间:2015-11-07 14:25:40

标签: c# json xml uwp json-deserialization

我有一个为uwp编写的c#客户端。

它有一个REST API客户端。

服务器代码是这样的:

*API Controller*

[HttpGet]
public IEnumerable<Services.Group> Get(Guid companyRef)
{
    return groupRepository.Get(companyRef);
}

模型是这样的:

public class Group
{
    public int GroupId { get; set; }
    public Guid GroupRef { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public Guid CompanyRef { get; set; }
    public bool Active { get; set; }
}

我的客户是这样的:

Uri uri = new Uri(Shared.URL);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Shared.HeaderType));
HttpResponseMessage response = await httpClient.GetAsync(uri + route + "?" + GeneralTags.COMPANY_REF + "=" + ApplicationObject.CompanyRef);
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
var objs = JArray.Parse(json); // parse as array  

ApplicationObject.GroupData = objs.Select(x => new Model.Group
{
    Description = (string)x[GeneralTags.DESCRIPTION],
    GroupRef = (Guid)shared.CheckForNulls(x[GeneralTags.GROUP_REF], typeof(Guid)),
    Name = (string)x[GeneralTags.NAME]
}).ToList();

但是,我现在正在替换:

ApplicationObject.GroupData = objs.Select(x => new Model.Group
{
    Description = (string)x[GeneralTags.DESCRIPTION],
    GroupRef = (Guid)shared.CheckForNulls(x[GeneralTags.GROUP_REF], typeof(Guid)),
    Name = (string)x[GeneralTags.NAME]
}).ToList();

这样,数据就包含在XML文档中了:

var doc = JsonConvert.DeserializeObject(json, typeof( XmlDocument));

但我得到一个错误:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Windows.Data.Xml.Dom.XmlDocument' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

虽然我理解错误消息告诉我的内容,但我不确定如何实施修复/更改

1 个答案:

答案 0 :(得分:0)

您可以尝试将对象反序列化为List,然后将该List序列化为XML。