且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中将JSON非对象转换为XML

更新时间:2023-01-23 08:08:58

这是一个相当复杂的JSON来解释,而不是特别的在我看来设计得很好。我认为要以一种看起来不错的格式自动将其转换为XML是很困难的,您可能需要对数据进行一些自己的解析。无论如何,这可能会让你开始,我没有实现所有的属性或对象,只是一些基本的骨架细节,所以你需要完成它。



有些课程



That's pretty complex JSON to interpret, and not particularly well designed in my opinion. I think it'll be hard to get something to convert that to XML automatically in a format that is going to look decent, you might need to do some of your own parsing of the data. This might get you started anyway, I haven't implemented all properties or objects, just some basic skeleton details so you'd need to finish it off.

Some classes

[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();