Java – How to read a json file and convert it to a POJO using GSON

How to read a json file and convert it to a POJO using GSON… here is a solution to the problem.

How to read a json file and convert it to a POJO using GSON

I need to pass values from a json file to a java class, and a json file is like this example:

    {
        "id":1,
        "name":"Gold",
        "description":"Shiny!",
        "spriteId":1,
        "consumable":true,
        "effectsId":[1]
    },

I

needed to map and I did it :

Items i = new Items();

Map<String, Items> mapaNomes = new HashMap<String, Items>();
mapaNomes.put("Gold",i);
mapaNomes.put("Apple",i );
mapaNomes.put("Clain Mail",i );

I’m new to android development and I may have forgotten something because the following doesn’t work, can someone help figure out what’s wrong?

BufferedReader in  = new BufferedReader(new InputStreamReader(System.in));

Gson gson = new Gson(); 
Items Items = gson.fromJson((BufferedReader) mapaNomes, Items.class);

Solution

1。 Create your POJO representation for your JSON.

public class MapaNomes() {
    String name;
    String description;
     etc

public String getName() {
        return name;
    }

 create your other getters and setters
}

I found this tool to convert json to POJO conveniently. http://www.jsonschema2pojo.org/

2。 Read your file.json. Turn it into an object

JsonReader reader = new JsonReader(new FileReader("file.json"));
MapaNomes mapaNomes = new Gson().fromJson(reader, MapaNomes.class);

Bonuses

I think you probably have many json objects in your file.json, for example:

{
    "id":1,
    "name":"Gold",
    "description":"Shiny!",
    "spriteId":1,
    "consumable":true,
    "effectsId":[1]
},
...
{
    "id":999,
    "name":"Silver",
    "description":"Whatever!",
    "spriteId":808,
    "consumable":true,
    "effectsId":[2]
},

If this is the case, then you can do the following:

JsonReader reader = new JsonReader(new FileReader("file.json"));
List<MapaNomes> mapaNomeses = new Gson().fromJson(
                                reader, 
                                new TypeToken<List<Review>>() {}.getType());

Then you can do whatever you want with each and every one of them

for (MapaNomes mapaNomes : mapaNomeses) {
     whatever
}

Related Problems and Solutions