jpp1
jpp1

Reputation: 2119

Parse JSON String into raw Java types using Jackson?

I would like to parse some JSON string the represents either an array or a map in the simplest possible way. I have the whole JSON string, no streaming is needed.

What I would like to do is something as similar as possible to this:

Object obj = parseJSON(theString);

Where obj would then hold an instance of either a Map or a List (I cannot know in advance which). The JSON object can be arbitrarily nested with maps and arrays but all types will be representable as basic Java types: String, Integer, Double, Boolean plus Map and ArrayList, nothing else.

All the simple examples I have found so far require me to know what the type is and which types I want, but I want to let all this do the JSON parser since I simply will not know in advance what I get.

If Jackson is not the best library to do this, what else could I use?

Upvotes: 1

Views: 5904

Answers (3)

jpp1
jpp1

Reputation: 2119

Silly question, simple answer:

import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.readValue(theString, Object.class);

That seems to do exactly what I want. And it's so obvious too!

Upvotes: 2

user949300
user949300

Reputation: 15729

Another option should you decide to ditch Jackson (Jackson is fine, I'm quite agnostic in the JSON wars) is json-simple.

JSONObject jObject = JSONValue.parse(String jsonString);

Since JSONObject extends java.util.HashMap everything should work.

Upvotes: 1

Vidya
Vidya

Reputation: 30310

All you need to do is this:

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

I'm pretty sure this returns a LinkedHashMap, if you care.

And in my opinion, you won't find a better serializer/deserializer for Java <-> JSON than Jackson. But there are many others like GSON.

Upvotes: 5

Related Questions