我的JSON值如下,
{ "emp_id": 1017,
"emp_name": "karthik Y",
"emp_designation": "Manager",
"department": "JavaJson",
"salary": 30000,
"direct_reports":
[
"Nataraj G",
"Kalyan",
"Mahitha"
]
}
HashMap < String, String[] >input1 = new HashMap < String, String[] >();
input1.put("empid","1017");
input1.put("emp_name","karthik");
input1.put("emp_designation","manager");
input1.put("salary","30000");
现在我想添加next_report的下一个数组作为下一个键和值(整个数组应该是一个键和值)。有人请帮忙。
答案 0 :(得分:2)
Hashmap是键/值存储,其中键是唯一的。您可以将JSON转换为字符串,然后将其作为值存储到hashmap中。例如,如下所示:
before_filter :authenticate
....
protected
def authenticate
domain = request.host
if domain == 'www.domain.hu'
authenticate_or_request_with_http_basic do |username, password| username == 'stuff' && password == 'boda'
end
elsif domain == 'www.domain.com'
authenticate_or_request_with_http_basic do |username, password| username == 'stuff' && password == 'boda'
end
end
end
您还需要使用“org.json”库
您还可以使用以下解决方案:
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 jar文件并将其放在类路径中以便能够使用JSONObject。您可以从here下载jar。
为了将每个值作为单个键/值条目放入映射中。你自己提到过,它应该没有任何问题。见下面的方法:
方法1 Java中的所有内容都是Object,String继承Object,String []继承对象。您可以拥有以下解决方案:
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");
方法2 要将字段存储为键/值,并且如果可以将数组转换为String(表示所有数组元素以逗号分隔,则使用此方法)。
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);
方法3 以Hash Map存储String key和Array值为代价。你必须把其他元素也作为数组。
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));
答案 1 :(得分:1)
使用jackson ObjectMapper。试试这是否有效
String json = "{....}"
HashMap<String,Object> mappedVals = new ObjectMapper().readValue(
json ,
new TypeReference<HashMap<String,Object>>() {
});