如何根据对象类型将JSON反序列化为两个不同的类?

wbrvyc0a  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(136)

我正在尝试读取以下格式的JSON文件:

{
    "A":
    {
        "type": "option_a",
        "state": 0,
    },
    
    "B":
    {
        "type": "option_b",
        "state": 1,
    },
    
    "C":
    {
        "type": "option_a",
        "state": 0,
    },
    
    .
    .
    .
    
    "Z":
    {
        "MODE A":
        {
            "status a": 0,
            "status b": 0,
        },
        "MODE B":
        {
            "status a": 0,
            "status b": 1,
        },
        "MODE C":
        {
            "status a": 1,
            "status b": 0,
        },
}

在我看来,相应的类应该是:

public class ClassA
{
    public string Type {get; set;}
    public int State {get; set;}
}

// for handeling the 'Z' structure:
public class ClassB
{
    public ClassBInternalStructure Mode {get; set;}
}

public class ClassBInternalStructure
{
    public int StatusA {get; set;}
    public int StatusB {get; set;}

我已经搜索了很多类似的问题,没有一个与这个案件的确切解决方案,就我设法找到。
如果我理解正确,正确的方法,这样的任务是使用Newtonsoft JsonConvert.这里是我已经带了到现在(C# 8),我会很感激任何帮助,以填补缺失的内容(希望我在正确的方向):

public class MyJsonConverter : JsonConverter
 {

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);
            if (token.Type == JTokenType.Object)
            {
                //????
            }
            else if (token.Type == JTokenType.String)
            {
                //????
            }
            else
            {
                throw new NotSupportedException("...");
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override bool CanConvert(Type objectType)
        {
            throw new NotImplementedException();
        }

    }

另一个我没想好的部分是如何调用这个方法-

public class JsonParser
{
        public void Parsing(string filePath)
        {
            try
            {
                using StreamReader sr = new(filePath);
                string JsonData = File.ReadAllText(filePath);

                // is another 'MyJsonConverter' override class needed?

                ???.ReadJson(????, null, null, new Newtonsoft.Json.JsonSerializer());
            }
            catch (Exception)
            {

                throw;
            }
        }
    }

先谢谢你!

pxyaymoc

pxyaymoc1#

校正类

public partial class test
{

    public A A { get; set; }

    public A B { get; set; }

    public A C { get; set; }

    public Dictionary<string, Z> Z { get; set; }
}

public partial class A
{

    public string Type { get; set; }

    public string State { get; set; }
}

public partial class Z
{

    public string StatusA { get; set; }

    public string StatusB { get; set; }
}

相关问题