Java将json字符串转Map
package com.util;
import net.sf.json.JSONArray;
js获取json的key和valueimport net.sf.json.JSONObject;
import java.util.Map;
public class JsonToMap {
private Object oJson;
public JsonToMap(Object jStr) {
this.oJson = jStr;
}
/**
* 将获取的value值封装给对象
* @param s value值
* @return 对象
*/
public JsonToMap get(Object s) {
if (s instanceof Integer) return new JsonToMap(JSONArray.fromObject(oJson).get((int) s));
else return new JsonToMap(jsonToMap(oJson).get(s));
}
@Override
public String toString() {
String();
}
public static void main(String[] args) {
String jsonStr = "{\"code\":\"0\",\"data\":{\"name\":\"Jackson\",\"age\":6},\"data1\":[{\"name\":\"Lee\",\"age\":18},{\"name\":\"Jack\",\"age\":20}]}"; JsonToMap jsonToMap = new JsonToMap(jsonStr);
System.out.println(jsonToMap);
System.out.("code"));
System.out.("data"));
System.out.("data").get("name"));//因为get⽅法返回的是JsonToMap对象,所以可以不断调⽤get(key)⽅法
System.out.("data").get("age"));
System.out.("data1"));
System.out.("data1").get(0));
System.out.("data1").get(1));
System.out.("data1").get(1).get("name"));
System.out.("data1").get(1).get("age"));
}
/**
* json string 转换为 map 对象
*
* @param jsonObj
* @return
*/
public static Map<Object, Object> jsonToMap(Object jsonObj) {
JSONObject jsonObject = JSONObject.fromObject(jsonObj);
Map<Object, Object> map = (Map) jsonObject;
return map;
}
}
运⾏结果:
{"code":"0","data":{"name":"Jackson","age":6},"data1":[{"name":"Lee","age":18}, {"name":"Jack","age":20}]} 0
{"name":"Jackson","age":6}
Jackson
6
[{"name":"Lee","age":18},{"name":"Jack","age":20}]
{"name":"Lee","age":18}
{"name":"Jack","age":20}
Jack
20
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论