c# - Unity parse nested Json [duplicate]

无人久伴 提交于 2019-12-12 04:43:01

问题


I have the following problem: I'm trying to parse a nested JSON using the Unity JsonUtility, but if i'm logging one of the nested parameters i get Null as a result.

Here's the Json:

{
    "basic": {
        "name": "Demo Bow" 
    }, 
    "effect": {
        "damage": {
            "stages": 3,
            "one": 4,
            "two": 10,
            "three": 40
        }
    }
}

And here's my code:

public class Basic
{
    public string name;
}

public class Damage
{
    public int stages;
    public int one;
    public int two;
    public int three;
}

public class Effect
{
    public Damage damage;
}

public class RootObject
{
    public Basic basic;
    public Effect effect;
}

Edit: No its not a duplicate, cause I already removed the "{ get; set; }" And heres the missing code.

public static RootObject CreateFromJSON(string json){

        RootObject weapon = JsonUtility.FromJson <RootObject> (json);


        return weapon;

    }

Thanks for any help


回答1:


You are missing the [System.Serializable] attribute on your classes, it is needed for JsonUtility to be able to serialize or deserialize your classes.

[System.Serializable]
public class Basic
{
    public string name;
}

[System.Serializable]    
public class Damage
{
    public int stages;
    public int one;
    public int two;
    public int three;
}

[System.Serializable]
public class Effect
{
    public Damage damage;
}

[System.Serializable]
public class RootObject
{
    public Basic basic;
    public Effect effect;
}


来源:https://stackoverflow.com/questions/47140672/c-sharp-unity-parse-nested-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!