Search code examples
javajsonjackson-databind

Prevent JSON within a map from losingJSON formatting


I have a JSON response that looks like this:

 {
  "id": "value",
  "screen": {
    "name": "Name",
    "properties": {
      "message": {
        "type": "string",
        "value": {
          "rawResponse": {
            "_links": {
              "self": {
                "href": "link"
              }
            },
            "_embedded": {},
            "id": "id"
          }
        }
      }
    }
  },
  "interactionId": "id"
}

With this Jackson Model:

package com.package;

import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
import java.util.Map;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

@Data
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PolicyStartResponse  {

  private String id;
  private Screen screen;

  @Data
  @SuperBuilder(toBuilder = true)
  @NoArgsConstructor
  @JsonInclude(JsonInclude.Include.NON_NULL)
  public static class Screen extends ApiModel<Screen> {

    private String name;
    private Map<String, Map<String, Object>> properties;
  }
}

For some reason when I extract the properties value it loses the quotes of the fields and the colons are replaced by equal signs.

      LinkedHashMap mapValue =
          (LinkedHashMap)
              response.getScreen().getProperties().get("message").get("value");
      mapper = new ObjectMapper();
      // For some reason retrieving the JSON from the map strips the quotes on fields.
      mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
      // For some reason the colons get translated to equal signs.
      String value = mapValue.get("rawResponse").toString();
      POJO p = mapper.readValue(value, POJO.class);

With this error:

JsonParseException: 
Unexpected character ('=' (code 61)): was expecting a colon to separate field name and value
 at [Source: (String)"{_links={self={href=

Any thoughts?


Solution

  • Was able to figure it out. JSONObject was able to handle it better.

    Here's the answer if anyone runs into this:

          JSONObject o = new JSONObject(response.getScreen().getProperties());
          POJO p = mapper.readValue(o.getJSONObject("message").getJSONObject("value").getJSONObject("rawResponse").toString(), PJOO.class);