【C#】复杂数据结构和Json的相互转换

数据结构定义
//数据结构定义
public class People
{
    public string name;
    public BaseInfo baseInfo;
    public List<School> education;
}
public class BaseInfo
{
    public int age;
    public bool gender;
    public List<Connection> connection;
}
注意一:Json结果展示枚举对于字符串

枚举数据转Json会转成对应数值

connectionWay = ConnectionWay.phone,
==>实际
"connectionWay" = 0,   
==>目标
"connectionWay" = “phone”, 

如果需要在json中展示枚举的字符串,需要增加

[JsonConverter(typeof(StringEnumConverter))]

public class Connection
{
    [JsonConverter(typeof(StringEnumConverter))] 
    public ConnectionWay connectionWay;
    public string text;
}
public enum ConnectionWay
{
    phone,
    email
}
注意二:Json结果展示私有变量

数据结构转Json过程中私有变量无法转换成功,需要增加

[JsonObject(MemberSerialization.OptIn)]定义在数据结构声明处

[JsonProperty]定义在需要json化私有变量声明处

[JsonObject(MemberSerialization.OptIn)]
public class School{
    [JsonProperty]
    private string name;
    [JsonProperty]
    private int completeYear;
    [JsonProperty]
    [JsonConverter(typeof(StringEnumConverter))]
    private EducationType educationType;
    
    private string address;
    public School(string name,int completeYear,EducationType educationType,string address = "")
    {
        ...;
    }
}
public enum EducationType
{
    highSchool,
    college
}
数据实例
People p = new People(){
    name = "Andy",
    baseInfo = new BaseInfo{
        age = 23,
        gender = false,
        connection = new List<Connection> {
            new Connection{
                connectionWay = ConnectionWay.phone,
                text = "88888888"
            },
            new Connection{
                connectionWay = ConnectionWay.email,
                text = "8888@123.com"
            }
        }
    },
    education = new List<School> {
        new School("某211",2017,EducationType.college,"北京市"),
        new School("某高级中学",2013,EducationType.highSchool,"孔子县")
    }
};
数据保存为Json文件
private void SaveData2JsonFile(string filePath)
{
    string json = JsonConvert.SerializeObject(p);
    using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath))
    {
        JObject jobject = JObject.Parse(json);
        file.Write(jobject.ToString());
    }
}

json文件内容

丢失School.address,由于定义时没有处理。

{
    "name":"Andy",
    "baseInfo":{
        "age" : 23,
        "gender" : false,
        "connection":[{
            "connectionWay":"phone",
            "text": "88888888"
        },{
            "connectionWay":"email",
            "text": "8888@123.com"
        }]
    },
    "education":[{
        "name":"某211",
        "completeYear":2017,
        "educationType":"college"
    },{
        "name":"某高级中学",
        "completeYear":2013,
        "educationType":"highSchool"
    }]
}
解析Json为对应数据结构实例

JsonUtility.FromJson<T>(json)

jObject["字段名"].ToObject<T>()

无法正确的转换List、嵌套数据结构等,只能解析简单数据结构

public void LoadJsonFile(string filePath)
{
    using (System.IO.StreamReader file = System.IO.File.OpenText(filePath))
    {
        using (JsonTextReader reader = new JsonTextReader(file))
        {
            Json2DataModel((JObject)JToken.ReadFrom(reader));
        }
    }
}
private void Json2DataModel(JObject jObject)
{
    List<School> education = new List<School>();
    foreach (var item in JArray.Parse(jObject["education"].ToString()))
    {
        education.Add(new School(
            item["name"].ToString(),
            int.Parse(item["completeYear"].ToString()),
            (EducationType)Enum.Parse(typeof(EducationType), item["educationType"].ToString())
        ));
    }

    BaseInfo baseInfo = jObject["baseInfo"].ToObject<BaseInfo>();
    List<Connection> connection = new List<Connection>();
    foreach (var item in JArray.Parse(jObject["baseInfo"]["connection"].ToString()))
    {
        ConnectionWay connectionWay = (ConnectionWay)Enum.Parse(typeof(ConnectionWay), item["connectionWay"].ToString());
        Connection conn = JsonUtility.FromJson<Connection>(item.ToString());
        connection.Add(conn);
    }
    baseInfo.connection = connection;

    People p = JsonUtility.FromJson<People>(jObject.ToString());
    p.baseInfo = baseInfo;
    p.education = education;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值