0

I have a JSONObject structured like this:

"data": {
   "title": "Pool Party",
   "date": {
       "start": "2018-08-14T15:44:44.625Z",
       "end": "2018-08-14T18:44:44.625Z"
}

and I'd like to convert it to

HashMap<String, String>

is there a way to structure the map in the same way for what regards the "start" and "end" field, which are under the "date" field?

I tried to convert it using Gson like this:

Type type = new TypeToken<Map<String, String>>(){}.getType();
HashMap<String, String> params = Gson().fromJson(jsonString, type);

but I got this error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT

probably because of the structure of my JSON string

Is there a way to get something like this? Thank you for your help.

2
  • Duplicate question Here already given a solution solution Commented Aug 29, 2018 at 1:36
  • it's not exactly what I want @Himly Commented Aug 29, 2018 at 2:00

2 Answers 2

1

You can use the ObjectMapper to convert it.

public void testJackson() throws IOException {  
    ObjectMapper mapper = new ObjectMapper(); 
    String json = "{"data": {"title": "Pool Party","date": {"start": "2018-08-14T15:44:44.625Z", "end": "2018-08-14T18:44:44.625Z"}}}"; 
    TypeReference<HashMap<String,Object>> typeRef 
            = new TypeReference<HashMap<String,Object>>() {};

    HashMap<String,Object> o = mapper.readValue(from, typeRef); 
    System.out.println("Got " + o); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

But I need it to be converted to HashMap<String, String> not HashMap<String, Object>
0

try something like this:

public void testJackson() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    String json = "{\"data\": {\"title\": \"Pool Party\",\"date\": {\"start\":\"2018-08-14T15:44:44.625Z\", \"end\":\"2018-08-14T18:44:44.625Z\"}}}";
    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
    };
    HashMap<String, Object> o = mapper.readValue(from, typeRef);
    System.out.println("Got " + o);
}

Comments

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.