Is it possible to have nested array json?

后端 未结 2 1099
一整个雨季
一整个雨季 2021-01-29 01:35

I\'m kinda new with json. So I want to make an array value inside a value of an array like below.

{
    \"id\": 0,
    \"title\": \"LEVEL\",
    \"value\": [10[2         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-29 02:18

    I always advice people to create a class and generate json from it instead of trying to construct json from your head. It's easier if you do it this way and the generated json will always be valid and exaclty what you wanted.

    This is what you want the json to look like:

    Here is what the structure should look like:

    [Serializable]
    public class Dialog
    {
        public Human human;
        public NonHuman nonHuman;
    }
    
    [Serializable]
    public class Human
    {
        public Inner inner;
        public Outer outer;
    }
    
    [Serializable]
    public class NonHuman
    {
        public string val;
    }
    
    [Serializable]
    public class Inner
    {
        public string[] val;
    }
    
    [Serializable]
    public class Outer
    {
        public string[] val;
    }
    

    Now, let's recreate what you have in that screenshot:

    //Create new dialog
    Dialog dialog = new Dialog();
    
    //Create nonhuman
    dialog.nonHuman = new NonHuman();
    dialog.nonHuman.val = "Once upon a time...";
    
    //Create human
    dialog.human = new Human();
    
    //Create human inner 
    dialog.human.inner = new Inner();
    dialog.human.inner.val = new string[2];
    dialog.human.inner.val[0] = "He is so scary";
    dialog.human.inner.val[1] = "She is so beautiful";
    
    //Create human outer 
    dialog.human.outer = new Outer();
    dialog.human.outer.val = new string[2];
    dialog.human.outer.val[0] = "Hey watch out !";
    dialog.human.outer.val[1] = "Look at her har !";
    
    //Convert to Json
    string json = JsonUtility.ToJson(dialog);
    //Show result in the Console tab
    Debug.Log(json);
    

    The generated Json result from Debug.Log:

    {"human":{"inner":{"val":["He is so scary","She is so beautiful"]},"outer":{"val":["Hey watch out !","Look at her har !"]}},"nonHuman":{"val":"Once upon a time..."}}
    

    See how I generated the valid json by creating a data structure of what you have in your screenshot, then creating new instance of it. That's the best way to do this. If this is not exactly what you wanted then your image is wrong. You can easily modify the data structure to get what you want.

提交回复
热议问题