2012-04-20 12 views
1

異なるString-Collectionsを1つのJSON 'String'にマージする方法はありますか? 私はこのようになりますJSON文字列を持っているしたいと思います:GSONを使用して複数のコレクション<String>を1つのJSON Stringにマージする

{"vendor":[Sun, HP, IBM],"product":[bla, bla, bla],"availability":[high, mid, low],"capacity":[bla, bla, bla], ...} 

これは私のJavaコードの一部です:

Collection<String> vendor = bh.getAllVendors(); 
Collection<String> product = bh.getProductsForVendor(vendor); 
Collection<String> availability = bh.getAllAvailabilities(); 
Collection<String> capacity = bh.getCapacityForVendor(vendor); 
Collection<String> signaling = bh.getSignalingForVendor(vendor); 
Collection<String> backup = bh.getBackupForVendor(vendor); 

Gson gson = new Gson(); 

任意の助けいただければ幸いです。

答えて

7

あなたがマップに追加する場合、それは最も簡単な次のようになります。

Gson gson = new Gson(); 

    Map<String, Collection<String>> map = new HashMap<>(); 
    map.put("vendor", vendor); 
    map.put("product", product); 
    //etc 

    System.out.println(gson.toJson(map)); 

は、このソリューションのための {"product":["bla","bla","bla"],"vendor":["Sun","IBM","HP"]}

+0

ニース。問題がある場合は、後でそれを逆直列化したい場合は、属性として 'vendor'、 'product'などのクラスを定義するか、カスタムデシリアライザを作成する必要があります。詳細については、[この質問]への回答(http://stackoverflow.com/questions/2779251/convert-json-to-hashmap-using-gson-in-java) – ArjunShankar

2

新しいクラスを作成します。

Class MyJSONObject 
    { 
    Collection<String> vendor; 
    Collection<String> product; 
    Collection<String> availability; 
    //... 
    //... 
    } 

その後MyJSONObjectのインスタンスにそれらの属性にデータを割り当てます。

そして、そのインスタンスをシリアライズ:

gson.toJson (myJSONObjectInstance); 

this GSON documentationの 'オブジェクトの例' のセクションをお読みください。

+0

感謝を生成します。私は受け入れられた答えにそれを好む。 –

関連する問題