C# - 将JSON字符串反序列化为Class

时间:2018-04-05 15:20:25

标签: c# json

我对C#很新,所以如果我问的是愚蠢的问题,请原谅。 我使用的是Newtownsoft JSON(https://www.newtonsoft.com/json

这是我的班级:

public class CharacterData
{
    public int characterId;
    public int connectionId;
    public int accountId;
    public string name;
    public int level;
    public int characterRace;
    public int characterClass;
    public CharacterPosition characterPosition;
    public CharacterRotation characterRotation;
    public CharacterInstance charactrerInstance;
    public CharacterState characterState;
    public CharacterMovementState characterMovementState;
    public CharacterActionState characterActionState;
    public CharacterEmotionState characterEmotionState;
    public string lastOnline;
    public string onlineTime;
}

public class CharacterPosition
{
    public string x;
    public string y;
    public string z;
    public int map; //Map id
}
public class CharacterInstance
{
    public int instanceId;
    public int groupId;
}
public class CharacterRotation
{
    public string x;
    public string y;
    public string z;
}

public class CharacterLearnedSpells
{
    public int spellId;
}

public enum CharacterState
{
    Alive,
    Dead,
    Ghost
}

public enum CharacterMovementState
{
    Standing,
    Walking,
    Running,
    Jumping,
}

public enum CharacterActionState
{
    Idle,
    Attacking,
    Casting,
}

public enum CharacterEmotionState
{
    Idle,
    Speaking,
    Questioning,
    Exclamating,
    Dancing,
    Insulting,
    Attacking,

}

这是我的json字符串:

{
    "1":
        {
            "characterId": 1,
            "connectionId": 1,
            "accountId": 1,
            "name": "Riorage",
            "level": 2,
            "characterRace": 1,
            "characterClass": 1,
            "characterPosition": {
                "x": "15.42661",
                "y": "7.477493",
                "z": "-32.30045",
                "map": 1

            },
            "characterRotation": {
                "x": "1",
                "y": "203",
                "z": "1"

            },
            "charactrerInstance": {
                "instanceId": 0,
                "groupId": 0

            },
            "characterState": 1,
            "characterMovementState": 0,
            "characterActionState": 1,
            "characterEmotionState": 1,
            "lastOnline": "5.4.2018 г. 14:59:16",
            "onlineTime": "1"
        }
}

以下是我尝试将此json解析为Characterdata类:

public void SpawnPlayer(Dictionary<string, string> playerData, int cnnId)    
{
    Debug.Log("Spawning..");
    CharacterData charData = new CharacterData();


    foreach (var item in playerData)
    {
        string jsonData = JsonConvert.SerializeObject(item.Value, Formatting.None);
        Debug.Log(jsonData);
        charData = JsonConvert.DeserializeObject<CharacterData>(jsonData);
    }
}

然而这不起作用。

以下是我收到的错误:

ArgumentException: Could not cast or convert from System.String to CharacterData.
Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable (System.Object value, System.Type initialType, System.Type targetType) (at C:/Project/Github/Json.Net.Unity3D/src/Newtonsoft.Json/Utilities/ConvertUtils.cs:668)

你能帮助我实现我想要的吗? 我想将此JSON字符串反序列化为类CharacterData。它甚至可能吗?

2 个答案:

答案 0 :(得分:1)

这是你的json,用&#34; \&#34;,\ r \ n和stuf修复。如需将来参考,请发布正确的json。

{
    "1":
        {
            "characterId": 1,
            "connectionId": 1,
            "accountId": 1,
            "name": "Riorage",
            "level": 2,
            "characterRace": 1,
            "characterClass": 1,
            "characterPosition": {
                "x": "15.42661",
                "y": "7.477493",
                "z": "-32.30045",
                "map": 1

            },
            "characterRotation": {
                "x": "1",
                "y": "203",
                "z": "1"

            },
            "charactrerInstance": {
                "instanceId": 0,
                "groupId": 0

            },
            "characterState": 1,
            "characterMovementState": 0,
            "characterActionState": 1,
            "characterEmotionState": 1,
            "lastOnline": "5.4.2018 г. 14:59:16",
            "onlineTime": "1"
        }
}

我认为你应该做的是:

  1. 首先创建一个与json
  2. 结构相同的类

    (我将发布此示例,您可以设置其他类和字段)

    public class CharacterData
    {
        [JsonProperty("characterId")] //if you want to reference the field coming in the json, this will allow you to have different name on the property below.
        public int characterId; 
        public int connectionId;
        public int accountId;
        public string name;
        public int level;
        public int characterRace;
        public int characterClass;
        public CharacterPosition characterPosition;
        public CharacterRotation characterRotation;
        public CharacterInstance charactrerInstance;
        public CharacterState characterState;
        public CharacterMovementState characterMovementState;
        public CharacterActionState characterActionState;
        public CharacterEmotionState characterEmotionState;
        public string lastOnline;
        public string onlineTime;
    }
    

    根据您获取json的方式,您可以从某个连接或某些字符串中检索它,但请注意json必须格式正确

    var deserialized = JsonConvert.DeserializeObject<CharacterData>(YourJsonStringOrResponseHere);
    
    var deserialized = JsonConvert.DeserializeObject<CharacterData>(await response.Content.ReadAsStringAsync());
    

答案 1 :(得分:0)

对我来说,一个很好的起点是在线查看一些可以做到这一点的在线网站。即JSON到C#类。试试这个:http://json2csharp.com/

它给了我很多帮助。