theJava
theJava

Reputation: 15034

Forming a JSON String using GSon

import java.util.HashMap;

public class JSON {

    public String name;

    public HashMap<String, String> Credentials = new HashMap<String, String>();

    public JSON(String name){
        Credentials.put(name, name);
    }

}

JSON json = new JSON("Key1");
new Gson().toJson(json);

I get the following value as output.

{"Credentials":{"Key1":"Key1"}}

Now how would i create an JSONObject something like this below using Gson.

Upvotes: 2

Views: 1706

Answers (2)

Dave G
Dave G

Reputation: 9777

Building on what @Brian is doing, you just need the auto serialization piece.

What you do is the following, and I have to state, this is with regard to a single object at the moment. You'll have to look through the GSON documentation for more detail on this if you're dealing with a collection of objects at the top level.

Gson gson= new Gson();
Writer output= ... /// wherever you're putting information out to
JsonWriter jsonWriter= new JsonWriter(output);
// jsonWriter.setIndent("\t"); // uncomment this if you want pretty output
// jsonWriter.setSerializeNulls(false); // uncomment this if you want null properties to be emitted
gson.toJson(myObjectInstance, MyObject.class, jsonWriter);
jsonWriter.flush();
jsonWriter.close();

Hopefully that will give you enough context to work with. Gson should be smart enough to figure out your properties and give them sensible names in the output.

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76908

You create a POJO that matches your JSON data structure:

public class MyObject {

    public HashMap<String,HashMap<String,String>> Credentials;
    public HashMap<String, String> Header;

}

Edit for comments below:

This is kinda "data structures 101" but ... you have a JSON Object that boils down to a Hash table that contains two hash tables, the first of which contains two more hash tables.

You can represent this simply as I show above, or you could create all the POJOs and use those:

public class Credentials {
    private PrimeSuiteCredential primeSuiteCredential;
    private VendorCredential vendorCredential;

   // getters and setters

}

public class PrimeSuiteCedential {
    private String primeSuiteSiteId;
    private String primeSuiteUserName;
    ...

    // Getters and setters
}

public class VendorCredential {
    private String vendorLogin;
    ...

    // getters and setters
}


public class Header {
    private String destinationSiteId;
    ...

    // getters and setters

}

public class MyObject {
    public Credentials credentials;
    public Header header;

    // getters and setters
}

Upvotes: 2

Related Questions