xploreraj
xploreraj

Reputation: 4362

Converting JSON string to Map with custom types

My JSON string is like this:

{
    "100": {
        "mode": 100,
        "enabled": true,
        "value": "someString"
    },
    "101": {
        "mode": 101,
        "enabled": false,
        "value": "someString"
    }
}

I have a class actually

class Mode {

    @JsonProperty("mode")
    long mode;

    @JsonProperty("enabled")
    boolean enabled;

    @JsonProperty("value")
    String value;

}

I tried

objectMapper.readValue(jsonString, Map.class); 

But its generic map and also the numbers are converted to Integer types not Long. Using Mode in place of Map above throws exception.

  1. How to get Long in generic Map?
  2. And, how can I get a Map<String, Mode> out of the json string?

I have got jackson library in my projects maven.

Upvotes: 1

Views: 184

Answers (1)

Khalid Shah
Khalid Shah

Reputation: 3232

your Key is String . It will work for you .

TypeReference<HashMap<String, Mode>> typeRef = new TypeReference<HashMap<String, Mode>>() {};
Map<String,Mode> map = objectMapper.readValue(jsonString,typeRef);

Updated :

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Mode {

  @JsonProperty("mode")
  long mode;

  @JsonProperty("enabled")
  boolean enabled;

  @JsonProperty("value")
  String value;

  @Override
  public String toString() {
    return "Mode{" +
        "mode=" + mode +
        ", enabled=" + enabled +
        ", value='" + value + '\'' +
        '}';
  }

  public static void main(String[] args) throws IOException {
    String json = "{\n"
        + "    \"100\": {\n"
        + "        \"mode\": 100,\n"
        + "        \"enabled\": true,\n"
        + "        \"value\": \"someString\"\n"
        + "    },\n"
        + "    \"101\": {\n"
        + "        \"mode\": 101,\n"
        + "        \"enabled\": false,\n"
        + "        \"value\": \"someString\"\n"
        + "    }\n"
        + "}";

    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<HashMap<String, Mode>> typeRef = new TypeReference<HashMap<String, Mode>>() {
    };
    Map<String, Mode> map = objectMapper.readValue(json, typeRef);
    map.entrySet().forEach(entry-> System.out.println(entry.getKey() + " : " +entry.getValue() ));
  }
}

Output :

100 : Mode{mode=100, enabled=true, value='someString'}
101 : Mode{mode=101, enabled=false, value='someString'}

Upvotes: 2

Related Questions