0

I have a JSON file called items.json, this is what is contained inside that file:

[
  {
    "id": 8484,
    "name": "David",
    "height": "6",
    "weight": 165,
  }
]

I am trying to use gson to print out the name and id.

I want it to Print out:

David 8484

I've searched for many examples but none work for this particular situation, or maybe they do but I am a beginner and need it simplified. Thanks for any help you can provide.

So my question is how can I achieve this? I will edit this question with my current code that isn't working in a minute, sorry.

4
  • 1
    What code do you have so far? Commented Aug 14, 2016 at 23:07
  • Sorry just realized it, going to edit it in in a second Commented Aug 14, 2016 at 23:07
  • Use Jackson JSON library and make this easy. Commented Aug 14, 2016 at 23:13
  • That is not valid JSON. The final comma must be removed. Commented Aug 14, 2016 at 23:21

1 Answer 1

1

The first thing, the JSON you show us is incorrect. Valid one would be:

[
  {
    "id": 8484,
    "name": "David",
    "height": "6",
    "weight": 165
  }
]

Last comma must be removed.

How to use Gson? It's easy. You need a class which will represent JSON as POJO (Plain Old Java Object). POJO is like skeleton. For you case I would write something like this:

public class Person {
    public int id;
    public String name;
    public int height;
    public int weight;
}

And then use Gson like this:

Gson gson = new Gson();
String json = "[{\"id\": 8484, \"name\": \"David\", \"height\": \"6\", \"weight\": 165}]";
//Because your JSON has array structure we need to give Gson array of our class
Person[] person = gson.fromJson(json, Person[].class);
//It will print: David 8484
System.out.println(person[0].name + " " + String.valueOf(person[0].id));

We don't need to give JSON as String, but fe. as reader of JSON file (FileReader).

If that didn't help, you propably don't have Gson in your project, but that is another question. Here is user guide for Gson: Gson User guide

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.