2016-12-28 84 views
1

我試圖使用json-simple 1.1.1發送API調用,並將字段和值保存爲HashMap。我應該把這些參數:如何將數組放入HashMap中以編碼JSON對象

{ api_key : string, 
    product_id : string, 
    name : string, 
    tax_rates : array } 

這裏是一個HashMap例如:

HashMap<String,Object> arg = new HashMap<String, Object>(); 
      arg.put("product_id","42"); 
      arg.put("name", "EKOS"); 
      arg.put("tax_rates", taxarray); 

我救taxarray作爲一個HashMap還有:

HashMap<String, Object> taxarray = new HashMap<String, Object>(); 
      taxarray.put("name","EKOS"); 
      taxarray.put("type", "type_value_fixed"); 
      taxarray.put("value", "56"); 

但是,當我執行的API調用它重新發生錯誤:參數'tax_rates'無效。所需的參數類型是一個數組。

我一直在嘗試將taxarray HashMap另存爲JSONArray。你能幫我解決這個問題嗎?

另一個問題:如何在一個「tax_rates」內保存2個或更多的稅率?這裏有一個例子:

HashMap<String,Object> arg = new HashMap<String, Object>(); 
       arg.put("product_id","42"); 
       arg.put("name", "EKOS"); 
       arg.put("tax_rates", array [ 
            taxarray1[], 
            taxarray2[] 
              ]); 
+0

作爲一個建議您應該使用Json對象來存儲對象,例如:{ 「product_id」:42, 「名稱」: 「EKOS」, 「tax_rates」:{ 「一」: 「B」, 「C」: 「d」, 「E」: 「F」 } } – user1211

+0

唔...我不會推薦這種方法。 'HashMap'不等同於JavaScript對象;其目的是捕獲實現相同接口的對象。雖然你可以得到這個工作,但它不是Java的方式。我會建議嘗試像https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/這樣的方法來使用現有工具將您的JSON映射到捕獲到的Java類您的期望結構更多的Java方式。 – sadakatsu

回答

1

你應該有這樣的事情 - 稅務類:

public class Tax { 
    String name; 
    String type; 
    Integer[] values; 

    public Tax(String name, String type, Integer[] values) { 
     this.name = name; 
     this.type = type; 
     this.values = values; 
    } 
} 

然後使用稅類代替HashMap中的對象的數組,tax_rates : array

該代碼使用谷歌JSON:

Map<String, Object> arg = new HashMap<String, Object>(); 
arg.put("product_id", "42"); 
arg.put("name", "EKOS"); 
arg.put("tax_rates", 
       new Tax[] { new Tax("EKOS", "type_value_fixed", new Integer[] { 1, 2, 3 }), 
         new Tax("ABC", "type_value_fixed", new Integer[] { 4, 5 }), 
         new Tax("DEF", "type_value_fixed", new Integer[] { 6, 7}) }); 

Gson gson = new Gson(); 

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

會給你這樣的JSON:

{ 
    "product_id": "42", 
    "name": "EKOS", 
    "tax_rates": [ 
    { 
     "name": "EKOS", 
     "type": "type_value_fixed", 
     "values": [ 
     1, 
     2, 
     3 
     ] 
    }, 
    { 
     "name": "ABC", 
     "type": "type_value_fixed", 
     "values": [ 
     4, 
     5 
     ] 
    }, 
    { 
     "name": "DEF", 
     "type": "type_value_fixed", 
     "values": [ 
     6, 
     7 
     ] 
    } 
    ] 
} 
+1

我推薦這個想法;即使他的項目架構也會更好。 –

0

tax_rates必須是一個數組,這樣做:

List<Double> taxRates = new ArrayList<Double>(); 
taxRates.add(19); 
taxRates.add(17.5); 

Map<String,Object> arg = new HashMap<String, Object>(); 
arg.put("product_id","42"); 
arg.put("name", "EKOS"); 
arg.put("tax_rates", taxRates);