0

I am using Gson for converting my Java Objects to GSON. I wanted to convert my HashMap to JSON.

Assuming my Object1 has structure:

public class Object1 {
     String a;
     String b;
     String c;

     String toString() {
          return "a: " + a + " b: " + b + " c: " + c;
     }
}

and my Object2 has Structure:

public class Object2 {
    String e;
    String f;
}

I wanted my final JSON to look like

{
    {
      "a" : "aValue",
      "b" : "bValue",
      "c" : "cValue"
    } : {
           "e" : "eValue",
           "f" : "fValue"
         } 
}

Bit I am getting it as

{
 "a: aValue b: bValue c: cValue" : {
        "e" : "eValue",
        "f" : "fValue"
  }
}

Is this possible to have it in desired form.

I tried using TypeToken given in JSON documentation. That didn't help.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

3 Answers3

0

Your toString() method may be causing issues, Gson will process the map itself, there is no need to provide a toString() like you have. That's why your output is giving you that.

Also take a look at Jackson, it would be fit for your purpose and is very easy to use.

Map map = new HashMap();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
// write json to file
sham
  • 3,691
  • 4
  • 15
  • 23
  • I don't think toString() is the cause. Because even it is not overrided, the Object1 also has a toString function. The reason is key in JSON can only be a string. That is one of the its difference from a Map in Java. – Cong Wang Sep 23 '16 at 09:35
  • I agree with @CongWang. I tried without toString and it mapped the object reference to the value – Mahima gupta Sep 23 '16 at 10:02
0

You cannot get your expected form.

JSON's element is always a key-value paar and the key is always a text (or String). But in your case the key is an object.

From my understanding, if you wanna to consume the key as an Object, you could get it as a String and then use ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper) to convert it to your expected class.

final ObjectMapper mapper = new ObjectMapper();
Object1 object1 = mapper.readValue(object1String, Object1.class)
Cong Wang
  • 769
  • 1
  • 9
  • 30
0

You can write your toString method as:

public String toString() {
    return "{a: " + a + ", b: " + b + ", c: " + c + "}";
}

In your main class, you call:

public static void main(String[] args) {
     Object1 object1 = new Object1("aValue", "bValue", "cValue");
     Object2 object2 = new Object2("eValue", "fValue");
     Map<String, Object2> map = new HashMap<String, Object2>();
     map.put(object1.toString(), object2);
     String json = new Gson().toJson(map);
}

Then, your output like: {"{a: aValue, b: bValue, c: cValue}":{"e":"eValue","f":"fValue"}}

Numb
  • 155
  • 3