本文介绍了在C#中将JSON非对象转换为XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我是一名Visual FoxPro开发人员,正在迁移到C#。我目前正在使用网络参考开发信用检查应用程序。我得到的响应是JSON,我试图将其转换为xml。我得到的问题是newton soft不想将JSON字符串/列表/非对象转换为C#。请协助,这是紧急的。



我尝试过:



我试过用xml节点转换,json转换,反序列化等等

Hi Guys, I'm a Visual FoxPro developer, migrating to C#. I'm currently developing a credit check app using web references. The response I get is in JSON and I'm trying to convert it to xml. The problem I get is that newton soft doesn't want to convert a JSON string/list/non-object to C#. Please assist, .

What I have tried:

I've tried converting with xml node, json convert, deserialization, etc

推荐答案

[Serializable]
public class CreditResult
{
    [XmlIgnore]
    public string Key { get; set; }

    [XmlIgnore]
    public List<JArray> Value { get; set; }

    [JsonIgnore]
    public ConsumerInfo ConsumerInfo { get; set; }
    [JsonIgnore]
    public LastAddress LastAddress { get; set; }
    [JsonIgnore]
    public CreditScore CreditScore { get; set; }
}

[Serializable]
public class ConsumerInfo
{
    public string RecordSeq { get; set; }
    public string Part { get; set; }
}

[Serializable]
public class LastAddress
{
    public string ConsumerNo { get; set; }
    public string InformationDate { get; set; }
}

[Serializable]
public class CreditScore
{
    public string ConsumerNo { get; set; }
    public List<string> PolicyFilters { get; set; }
    public List<Indicator> Indicators { get; set; }
}

[Serializable]
public class Indicator
{
    public string Type { get; set; }
    public string Score { get; set; }
}










CreditResult result = JsonConvert.DeserializeObject<List<CreditResult>>(Item).FirstOrDefault();

foreach (JArray subArray in result.Value)
{
    foreach (JObject obj in subArray)
    {
        string objType = obj.GetValue("Key").Value<string>(); // Consumer Info, Last Address etc

        switch (objType)
        {
            case "ConsumerInfo":
                ConsumerInfo consumerInfo = obj.GetValue("Value").ToObject<ConsumerInfo>();
                result.ConsumerInfo = consumerInfo;
                break;
            case "LastAddress":
                LastAddress lastAddress = obj.GetValue("Value").ToObject<LastAddress>();
                result.LastAddress = lastAddress;
                break;
            case "CreditScore":
                CreditScore creditScore = obj.GetValue("Value").ToObject<CreditScore>();
                result.CreditScore = creditScore;
                break;
        }
    }
}

XmlSerializer s = new XmlSerializer(typeof(CreditResult));
MemoryStream memStream = new MemoryStream();
s.Serialize(memStream, result);
memStream.Position = 0;

string xml = new StreamReader(memStream).ReadToEnd();


这篇关于在C#中将JSON非对象转换为XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:51