import java.util.Map;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class Test {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String json = "{\"user\":\"11\", \"name\":{\"FirstName\":\"tht\",\"LastName\":\"Tang\"}, "
+ "\"list\":[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]}";
JSONObject Object = JSONObject.parseObject(json);
System.out.println(Object); //{"list":[{"name":"a","value":"aa"},{"name":"b","value":"bb"},{"name":"c","value":"cc"},{"name":"d","value":"dd"}],"Name":{"FirstName":"tht","LastName":"Tang"},"UserID":"11"}
Integer user =Integer.parseInt(Object.get("user").toString());
System.out.println(user); //11
System.out.println(Object.get("name").toString());
//{"FirstName":"tht","LastName":"Tang"}
Map<String,String> name = Object.getObject("name", Map.class);
String fName = name.get("FirstName");
System.out.println(fName);//tht
JSONArray jsonArray = Object.getJSONArray("list");
System.out.println(jsonArray); //[{"name":"a","value":"aa"},{"name":"b","value":"bb"},{"name":"c","value":"cc"},{"name":"d","value":"dd"}]
Map<String,String> listMap = jsonArray.getObject(0, Map.class);
System.out.println(listMap.get("name"));//a
//转为list
List<Map<String, String>> javaObject = JSONArray.toJavaObject(jsonArray, List.class);
for (Map<String, String> map : javaObject) {
System.out.println(map.get("name"));
}
String string = jsonArray.getJSONObject(0).get("name").toString();
System.out.println(string); //a
}
}
Json字符串转为map或数组或集合
最新推荐文章于 2024-01-15 17:03:12 发布