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<String, String> jsonStore = new HashMap<String, String>();
jsonStore.put("myJson", json);
System.out.println(jsonStore.get("myJson"));
}
你需要也可以使用'org.json'库来
- 手动创建 JSON 对象
- 将现有 JSONObject 转换为字符串表示形式
- 将 JSON 字符串转换为 JSONObject
您还可以有以下解决方案:
JSONObject jsonObject = new JSONObject();
jsonObject.put("empt_id", 1017);
jsonObject.put("emp_name", "karthik");
HashMap<String, JSONObject> jsonObjectStore = new HashMap<String, JSONObject>();
jsonObjectStore.put("myJsonObject", jsonObject);
HashMap<JSONObject, String> jsonObjectStore2 = new HashMap<JSONObject, String>();
jsonObjectStore2.put(jsonObject, "myJson");
确保您下载了 org.json jar 文件并将其放在您的类路径中,以便能够使用 JSONObject。你可以从here下载jar。
为了将这些值中的每一个作为单个键/值条目放入映射中。您自己已经提到过,它应该可以正常工作。见以下方法:
方法一
Java 中的一切都是 Object,String 继承 Object,String[] 继承 object。您可以有以下解决方案:
HashMap<String, Object> myObjectStore4 = new HashMap<String, Object>();
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);
方法二
要将字段存储为键/值,并且如果您负担得起将数组转换为字符串(表示所有数组元素以逗号分隔,则使用此方法)。
HashMap<String, String> myObjectStoreTwo = new HashMap<String, String>();
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));
方法三
以使用 Hash Map 存储 String 键和 Array 值为代价。您也必须将其他元素作为数组。
HashMap<String, String[]> myObjectStore3 = new HashMap<String, String[]>();
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);