4

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

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

i need to map,i did this:

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'm probably forgetting something because the following is not working,someone can help in find what`s is wrong?

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

Gson gson = new Gson(); 
Items Items = gson.fromJson((BufferedReader) mapaNomes, Items.class);
2
  • Why are you casting a Map to a BufferedReader which has nothing to do with the json? Commented Oct 23, 2015 at 1:29
  • DataObject obj = gson.fromJson(br, DataObject.class); first convert your json reponse to DataObject and then map it. here br is BufferedReader object Commented Oct 23, 2015 at 1:34

1 Answer 1

6

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 find this tool is handy for transforming json to POJO. http://www.jsonschema2pojo.org/

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

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

Bonus

I'm thinking that there might be numerous json objects in your file.json such as:

{
    "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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.