1

I am new to stackoverflow.

I am creating an Java application which it will get data from a web server. The data is in json format. Example"

[
  {
    "item_name": "Adame",
    "item_type": "Special",
    "item": "Chestplate",
    "item_min_lvl": "50",
    "enchantment": {
      "health": "0.3",
      "dam": "24%",
      "life": "0.1",
      "xp": "24%",
      "loot": "22%"
    },
    "def": "73"
  },
  {
    "item_name": "Sticks'",
    "item_type": "Unique",
    "item": "Stick",
    "item_min_lvl": "4",
    "enchantment": {
      "health": "0.6",
      "mana": "1",
      "dam": "12%",
      "life": "0.3",
      "xp": "17%",
      "loot": "17%"
    },
    "min_dam": "39",
    "max_dam": "34"
  }
]

I know how to deserialize json using Gson. As you can see, it's started with [. I never deserialize this case before. Also, the json data is not the same(e.g. enchantment). I also searched in Google but I can't find any similar case. Can anyone help me with the code?

8
  • The enclosing [ and ] just mean that the data is an array of objects. Commented May 17, 2014 at 10:11
  • @geoand Yea i know. But how can I deserialize it? Usually it will like this Data[] data; but there is no data before [ Commented May 17, 2014 at 10:17
  • Go to json.org and learn the JSON syntax. It only takes 5-10 minutes to learn. Sometimes the outer layer of a JSON string is an object (Map) sometimes an array (List). It simply depends on the data being described. Commented May 17, 2014 at 12:03
  • And if you don't know what a Map or a List is, study up on those before you try to tackle JSON. Commented May 17, 2014 at 12:05
  • @HotLicks I said I know JSON. Actually I just don't know how to deserialize it... Commented May 17, 2014 at 12:34

2 Answers 2

0

Try with this code. You will get the answer of your question. It's an List with 2 items.

StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(new File("resources/json1.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
    builder.append(line);
}
reader.close();

Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<MyJSON>>() {
}.getType();
List<MyJSON> list = gson.fromJson(builder.toString(), listType);
// you can try this form as well
// MyJSON[] list = gson.fromJson(builder.toString(), MyJSON[].class);

for (MyJSON json : list) {
    System.out.println(json.toString());
}

...

class MyJSON {
    String item_name;
    String item_type;
    String item;
    String item_min_lvl;
    Enchantment enchantment;

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();

        builder.append("\nitem_name:").append(item_name);
        builder.append("\nitem_type:").append(item_type);
        builder.append("\nitem:").append(item);
        builder.append("\nitem_min_lvl:").append(item_min_lvl);

        builder.append("\n\nEnchantment Details:");
        builder.append("\nhealth:").append(enchantment.health);
        builder.append("\ndam:").append(enchantment.dam);
        builder.append("\nlife:").append(enchantment.life);
        builder.append("\nxp:").append(enchantment.xp);
        builder.append("\nloot:").append(enchantment.loot);
        return builder.toString();
    }
}

class Enchantment {
    String health;
    String dam;
    String life;
    String xp;
    String loot;
}

output:

item_name:Adame
item_type:Special
item:Chestplate
item_min_lvl:50

Enchantment Details:
health:0.3
dam:24%
life:0.1
xp:24%
loot:22%


item_name:Sticks'
item_type:Unique
item:Stick
item_min_lvl:4

Enchantment Details:
health:0.6
dam:12%
life:0.3
xp:17%
loot:17%

EDIT

The structure of each entry is not same hence you can't use POJO for this type of JSON.

Simply use ArrayList<Map<String, Object>> and access the value based on key from the map.

Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Map<String, Object>>>() {
}.getType();
ArrayList<Map<String, Object>> list = gson.fromJson(builder.toString(), listType);

for (Map<String, Object> json : list) {
    for (String key : json.keySet()) {
        System.out.println(key + ":" + json.get(key));
    }
    System.out.println("===========");
} 

output:

item_name:Adame
item_type:Special
item:Chestplate
item_min_lvl:50
enchantment:{health=0.3, dam=24%, life=0.1, xp=24%, loot=22%}
def:73
===========
item_name:Sticks'
item_type:Unique
item:Stick
item_min_lvl:4
enchantment:{health=0.6, mana=1, dam=12%, life=0.3, xp=17%, loot=17%}
min_dam:39
max_dam:34
===========
Sign up to request clarification or add additional context in comments.

14 Comments

nop. com.google.gson.internal.LinkedTreeMap i got this
@user3646662 I think now you can proceed.
@user3646662 Here is the complete updated in post. Its array not map.
@user3646662 If still you are getting Map then modify my program accordingly.
Thanks! <3 I will try it soon. Btw you forgot to put mana, def and "min_dam and max_dam
|
0

This is actually valid in Java and with GSON:

YourObject[] locs = gson.fromJson (someJsonString, YourObject[].class);

It'll parse and return an array of YourObject. Just create Java Classes that represent your JSON objects, and replace the placeholders as necessary.

EDIT: As Braj said before, you can create a fully formed POJO, including the other, (non-symmetrical) attributes (I'm borrowing the code from from Braj's answer here):

//... snip ...
class MyJSON
{
    String      item_name;
    String      item_type;
    String      item;
    String      item_min_lvl;
    Enchantment enchantment;

    // Heres the other attributes
    String      min_dam;
    String      max_dam;
}
//... snip ...

GSON will parse it and set the values to null if they aren't provided in the original JSON.

However, from the other question, it seems that the JSON (Java - JSON Parser Error) for enchantment is provided inconsistently, so this will cause issues. I would recommend sending JSON for enchantment as an array for consistency, then you could structure your POJO as:

 //... snip ...
class MyJSON
{
    String      item_name;
    String      item_type;
    String      item;
    String      item_min_lvl;
    Enchantment[]   enchantment;

    // Heres the other attributes
    String      min_dam;
    String      max_dam;
}
//... snip ...

9 Comments

Please share the code. What will be the structure of YourObject here? Look at the JSON string again, it's not symmetric.
And for you information I have already shared this line in my post.
@Braj Sorry, didn't notice, had this question open for a while. You can have a fully formed POJO with min_dam and max_dam as a String attributes. GSON will parse it and just set the values to null if they aren't set in the original JSON anyway. An example from your MyJSON above: class MyJSON { String item_name; String item_type; String item; String item_min_lvl; Enchantment enchantment; String min_dam; String max_dam; } You can make a distinction between the types by checking if those values are null
The values are dynamic. some time "enchantment": {}, "enchantment": [] or not at all.
Yes you can add more information in your post to make it clear.
|

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.