libgdx Json parsing

前端 未结 1 1480
死守一世寂寞
死守一世寂寞 2021-01-03 10:03

hi I\'m trying to get all \'id\' value from my json into my \'results\' array.

I didn\'t really understood how the json class of libgdx works, but I know how json wo

1条回答
  •  伪装坚强ぢ
    2021-01-03 10:48

    Doing it this way will result in a very hacky, not maintainable code. Your JSON file looks very simple but your code is terrible if you parse the whole JSON file yourself. Just imagine how it will look like if you are having more than an id, which is probably going to happen.

    The much more clean way is object oriented. Create an object structure, which resembles the structure of your JSON file. In your case this might look like the following:

    public class Data {
    
        public Array table;
    
    }
    
    public class TableEntry {
    
        public int id;
    
    }
    

    Now you can easily deserialize the JSON with libgdx without any custom serializers, because libgdx uses reflection to handle most standard cases.

    Json json = new Json();
    json.setTypeName(null);
    json.setUsePrototypes(false);
    json.setIgnoreUnknownFields(true);
    json.setOutputType(OutputType.json);
    
    // I'm using your file as a String here, but you can supply the file as well
    Data data = json.fromJson(Data.class, "{\"table\": [{\"id\": 1},{\"id\": 2},{\"id\": 3},{\"id\": 4}]}");
    

    Now you've got a plain old java object (POJO) which contains all the information you need and you can process it however you want.

    Array results = new Array();
    for (TableEntry entry : data.table) {
        results.add(entry.id);
    }
    

    Done. Very clean code and easily extendable.

    0 讨论(0)
提交回复
热议问题