Daniel Von Lincoln Daniel Von Lincoln -4 years ago 102
Java Question

Getting a Hashtable from Gson

I have a .json file storing the value of a hashtable

{FISH:{class:java.lang.Integer,value:7},EGGS:{class:java.lang.Integer,value:6},CHICKEN:{class:java.lang.Integer,value:7}}

I save the table no problem:

private void saveInventory()
{
Json json = new Json();
file.writeString(json.prettyPrint(inventory.inv), false);
}


I am trying to load that table using Gson.

I have tried a couple of different ways based on several other questions on here. Each have given different errors, malformedJsonException, currently have the below and it's giving me the error: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT

private void loadInventory() {
Json json = new Json();
Gson gson = new Gson();

try {
BufferedReader br = new BufferedReader(new FileReader("bin/data.json"));
JsonObject object = (JsonObject) new com.google.gson.JsonParser().parse(br);
Set<Map.Entry<String, JsonElement>> set = object.entrySet();
Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();

Hashtable<Constants.FoodTypes, Integer> map = new Hashtable<Constants.FoodTypes, Integer>();

while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();

Constants.FoodTypes value = gson.fromJson(entry.getValue(), Constants.FoodTypes.class);
Integer key = Integer.parseInt(entry.getKey());

if (value != null) {
map.put(value, key);
}

}

}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}


What is a better way to load this back as a hashtable?

Answer Source

"{FISH:{class:java.lang.Integer,value:7},EGGS:{class:java.lang.Integer,value:6},CHICKEN:{class:java.lang.Integer,value:7}}" is not a proper JSON object. You could create the file (or string) by using Gson to generate it from a hashtable.

In this case, your json string should be

{
  "FISH": {
    "class": "java.lang.Integer",
    "value": 7
  },
  "EGGS": {
    "class": "java.lang.Integer",
    "value": 6
  },
  "CHICKEN": {
    "class": "java.lang.Integer",
    "value": 7
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download