2
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);

次の値を出力として取得します。

{"クレデンシャル":{"Key1": "Key1"}}

では、Gsonを使用して以下のようなJSONObjectを作成するにはどうすればよいでしょうか。

4

2 に答える 2

2

JSONデータ構造に一致するPOJOを作成します。

public class MyObject {

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

}

以下のコメントを編集してください。

これはちょっと「データ構造101」ですが...2つのハッシュテーブルを含むハッシュテーブルに要約されるJSONオブジェクトがあり、最初のハッシュテーブルにはさらに2つのハッシュテーブルが含まれています。

上に示したようにこれを簡単に表すことも、すべてのPOJOを作成してそれらを使用することもできます。

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
}
于 2012-10-22T10:23:46.177 に答える
1

@Brianが行っていることに基づいて、自動シリアル化のピースが必要です。

あなたがしていることは次のとおりです、そして私が言わなければならないのは、これは現時点で単一のオブジェクトに関するものです。トップレベルでオブジェクトのコレクションを処理している場合は、GSONのドキュメントで詳細を確認する必要があります。

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();

うまくいけば、それはあなたに作業するのに十分なコンテキストを与えるでしょう。Gsonは、プロパティを理解し、出力で適切な名前を付けるのに十分なほど賢いはずです。

于 2012-10-22T11:58:40.370 に答える