Is there a Java JSON deserializer that decodes a string into dictionary of lists or lists of dictionaries of primitive types

12,581

Solution 1

Almost every single Java library at http://json.org/ can do this, did you actually try finding something?

For example, with Jackson you would do:

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);

but it is often convenient to create your own Java objects to map to; there is no need to use standard objects. For example:

  public class MyType {
    public String name;
    public int age;
    // and so on
    public Date createTime;
  }

  MyType instance = mapper.readValue(json, MyType.class);

For more examples, you can check out Jackson tutorial.

Solution 2

Rather than trying to force JSON into a difficult to use Map<String, Object> or List<Object>, I'd recommend a library that can parse JSON into a tree model. While many libraries can do this sort of thing, Google Gson is my favorite. You can use its JsonParser class to parse JSON as a tree starting with a root JsonElement. Once you have the JsonElement, it should be considerably easier to use than some Object that might be a List and might be a Map.

JsonElement e = new JsonParser().parse(someJson);
if (e.isJsonObject()) {
  // JsonObject has many of the same methods as a Map
  JsonObject obj = e.getAsJsonObject();
  String foo = obj.get("foo").getAsString();
  int bar = obj.get("bar").getAsInt();
} else if (e.isJsonArray()) {
  JsonArray array = e.getAsJsonArray();
  // JsonArray implements Iterable and can be used a lot like a List
  for (JsonElement element : array) {
    ...
  }
}

It's easy to build a JSON tree using these objects as well.

Solution 3

Flexjson definitely does it. The below line de-serialize a jsonString to a HashMap

Map<String, String> map = new flexjson.JSONDeserializer().deserialize(jsonString);
Share:
12,581
ada
Author by

ada

Updated on June 05, 2022

Comments

  • ada
    ada almost 2 years

    I need to pull back from a database JSON documents that are not based on a standard object.

    Is there a way using JAVA to "deserialize" these documents into Lists & Dictionaries of primitive objects (string, int, bool, etc...)

    Any library that can do this in both directions? In other words I am looking for the Java counter part of System.Runtime.Serialization.Json