将JSON值放入Hashmap

我有如下JSON值,

{ "emp_id": 1017, "emp_name": "karthik Y", "emp_designation": "Manager", "department": "JavaJson", "salary": 30000, "direct_reports": [ "Nataraj G", "Kalyan", "Mahitha" ] } HashMap input1 = new HashMap (); input1.put("empid","1017"); input1.put("emp_name","karthik"); input1.put("emp_designation","manager"); input1.put("salary","30000"); 

现在我想添加下一个数组,即direct_report作为下一个键和值(整个数组应该是一个键和值)。 有人请帮忙。

Hashmap是键/值存储,其中键是唯一的。 您可以将JSON转换为字符串,然后将其作为值存储到hashmap中。 例如下面的内容:

 public static void main(String[] args) { String json = "{ \"emp_id\": 1017," + "\"emp_name\": \"karthik Y\"," + "\"emp_designation\": \"Manager\"," + "\"department\": \"JavaJson\"," + "\"salary\": 30000," + "\"direct_reports\": [" + "\"Nataraj G\"," + "\"Kalyan\"," + "\"Mahitha\"]}"; HashMap jsonStore = new HashMap(); jsonStore.put("myJson", json); System.out.println(jsonStore.get("myJson")); } 

您还需要使用’ org.json ‘库

  • 手动创建JSON对象
  • 将现有JSONObject转换为String表示forms
  • 将JSON字符串转换为JSONObject

您还可以使用以下解决方案:

 JSONObject jsonObject = new JSONObject(); jsonObject.put("empt_id", 1017); jsonObject.put("emp_name", "karthik"); HashMap jsonObjectStore = new HashMap(); jsonObjectStore.put("myJsonObject", jsonObject); HashMap jsonObjectStore2 = new HashMap(); jsonObjectStore2.put(jsonObject, "myJson"); 

确保下载org.json jar文件并将其放在类路径中以便能够使用JSONObject。 你可以从这里下载jar。

为了将每个值放入映射中作为单个键/值输入。 你自己提到过,它应该没有任何问题。 见下面的方法:

方法1 Java中的所有东西都是Object,StringinheritanceObject,String []inheritance对象。 您可以拥有以下解决方案:

 HashMap myObjectStore4 = new HashMap(); String[] directReports4 = new String[]{"Natraj G", "Kalyan", "Mahitha"}; myObjectStore4.put("emp_id", new String("123")); myObjectStore4.put("emp_name", new String("Raf")); // others .... myObjectStore4.put("directReports", directReports4); 

方法2将字段存储为键/值,如果您能负担将数组转换为String(表示所有数组元素以逗号分隔,则使用此方法)。

 HashMap myObjectStoreTwo = new HashMap(); String[] directReports2 = new String[]{"Natraj G", "Kalyan", "Mahitha"}; myObjectStoreTwo.put("emp_id", "123"); myObjectStoreTwo.put("emp_name", "Raf"); myObjectStoreTwo.put("salary", "222"); //Converts array to comma separated String myObjectStoreTwo.put("directReports",Arrays.toString(directReports2)); 

方法3以使用Hash Map存储String key和Array值为代价。 你必须把其他元素也作为数组。

 HashMap myObjectStore3 = new HashMap(); String[] directReports3 = new String[]{"Natraj G", "Kalyan", "Mahitha"}; myObjectStore3.put("emp_id", new String[]{123 + ""}); myObjectStore3.put("salary", new String[]{32312 + ""}); myObjectStore3.put("directReports", directReports3); 

使用jackson ObjectMapper。 试试这是否有效

 String json = "{....}" HashMap mappedVals = new ObjectMapper().readValue( json , new TypeReference>() { });