Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON response with dash in the key-name

I am using feign for my rest-calls. Unfortunately one of the responses I get looks something like this:

{
    "customer-id" : "0123"
}

The JSON response automatically gets mapped to one of my POJO's. This response object can not have a property field with the name "customer-id", as the dash (-) is not allowed in the name of an identifier.

I tried the following:

public class LookUpAccountsResponse {
        @JsonProperty("customer-id")
        private String customerId;
}

But unfortunately this doesn't work. Does anyone have a suggestion on how to fix this?

like image 247
Robert van der Spek Avatar asked Apr 21 '17 07:04

Robert van der Spek


People also ask

Can JSON key have dash?

In javascript, you cannot access properties which have a dash in them using this syntax.

Does JSON need quotes around keys?

JSON is based on JavaScript but the format is stricter. JSON requires double quotes around keys whereas JavaScript does not.

How do you name a JSON key?

According to JSON.org, a string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. Any valid string can be used as a JSON key. These keys must be enclosed in the double-quotes ( " ). This means if the key name contains any double quote in it, then it must be escaped.

How do I change the key in a JSON response?

Changing key names or values If you need to change all instances of a key or value with a different one, just use the SUBSTITUTE() function. You'll need to copy and paste the value of the cell into another using Ctrl + Shift + V or Cmd + Shift + V to see the actual change in the JSON.


2 Answers

com.google.gson.GsonDecoder

Not sure why JsonProperty is on your classpath, but see "field naming support" https://github.com/google/gson/blob/master/UserGuide.md#json-field-naming-support

@SerializedName is the Gson annotation you'll want

Or switch entirely to using the feign-jackson dependency with a JacksonDecoder

like image 82
OneCricketeer Avatar answered Oct 19 '22 17:10

OneCricketeer


It works fine. Here is a minimal example:

  public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    SomeClass sc = new ObjectMapper().readValue("{\"property-with-dash\": 5}", SomeClass.class);

    System.out.println(sc.propertyWithDash);
  }

  public static class SomeClass {
    @JsonProperty("property-with-dash")
    private int propertyWithDash;
  }

This prints 5 as expected. No complaints.

like image 24
john16384 Avatar answered Oct 19 '22 17:10

john16384