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.

Rubick
  • 280
  • 1
  • 20
Mantech
  • 59
  • 1
  • 8
  • Duplicate question Here already given a solution [solution](https://stackoverflow.com/questions/2525042/how-to-convert-a-json-string-to-a-mapstring-string-with-jackson-json) – Himly Aug 29 '18 at 01:36
  • it's not exactly what I want @Himly – Mantech Aug 29 '18 at 02:00

2 Answers2

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); 
}
Himly
  • 384
  • 2
  • 16
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);
}
Saeed Zhiany
  • 1,923
  • 7
  • 25
  • 34