简体   繁体   中英

I want Parse Json using MiniJson and store it in a list for manipulation

    {
    "players": [
    {
    "wins": 8,
    "losses": 1,
    "score": 264.5,
    "pro": false,
    "name": "albert"
    },
    {
    "wins": 7,
    "losses": 1,
    "score": 214.5,
    "pro": false,
    "name": "mike"
    }

I want to parse it and I have tried as below:

    Dictionary<string,object> data=MiniJSON.Json.Deserialize(json) as Dictionary<string,object>;
    List<object> list=(List<object>)(data["Person"]);
    //data["players"] as List<object>
    foreach(var item in data)
    {
     // data as Dictionary<string,object>
    Dictionary<string,object> dict=(Dictionary<string,object>)(data);
    }

I Tried But I don't know whether It is coorect or not and I Have not able to proceed further please spare a minute to help me

1) Your Json is not valid: you can use this site to validate json. You should add ']' and '}'. So you json should look like:

{
    "players": 
    [
        {
            "wins": 8,
            "losses": 1,
            "score": 264.5,
            "pro": false,
            "name": "albert"
        },
        {
            "wins": 7,
            "losses": 1,
            "score": 214.5,
            "pro": false,
            "name": "mike"
        }
    ]
}

2) You can use Unity JsonUtility. Create class Player

[Serializable]
public class Player
{
    int wins;
    int losses;
    int score;
    bool pro;
    string name;
}

Then create player container

public class PlayerContainer
{
    List<Player> players = new List<Player>();
}

Now you can use JsonUtility to serialize/deserialize your data

public class PlayersController
{
    private void Start()
    {
        string json = "your json";
        var players = JsonUtility.FromJson<PlayerContainer>(json);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM