0

Hi I have a Java Class like,

// code
class A{
  private int i;
  private String j;
// getters/setters
}

I want to use this object as a map key in my json, how i can do this? e.g : i want something like - {javaObject:value}

Kumar-Sandeep
  • 202
  • 1
  • 4
  • 14

3 Answers3

0

In that case when you want to convert object to json, use this link. Gson can be used to do that.

Ashutosh Jha
  • 1,465
  • 1
  • 17
  • 28
  • It's not working as it uses the objects tostring, also below link says that it is not possible:- http://stackoverflow.com/questions/11628698/can-we-make-object-as-key-in-map-when-using-json – Kumar-Sandeep Oct 19 '16 at 09:27
0

You can bind key with any object and map the key-name with json key, use Jackson library to achieve this -

1.You can create data binding POJO like below -

  class A{

  @JsonProperty("key_name")
  private int i;
  @JsonProperty("key_name")
  private String j;
 // getters/setters

}

2.If you want Object A to be used as a key, then create a pojo like below -

 class JsonData{
 @JsonProperty("key_name")
 private A object;
 //getter //setter
 }
Derrick
  • 3,669
  • 5
  • 35
  • 50
0

Hi I've find the correct answer, actually for complex object as a map key in JSON we have to use:-

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.enableComplexMapKeySerialization();
Gson mapper = gsonBuilder.create();
//Object to JSON in String
String jsonInString = mapper.toJson(myobject); //myobject=any object of class A
Kumar-Sandeep
  • 202
  • 1
  • 4
  • 14