您的位置:首页 > 编程语言 > Java开发

java中json的使用

2016-07-13 13:20 573 查看
String s = "src/text/multipleJson.js";
System.out.println(s);
//将前台传来的json变成java中class对象
String ss = ToString.readData(s);
System.out.println(ss);

Semantics ds=new Semantics();
Gson gson = new Gson();
ds = gson.fromJson(ss, Semantics.class);
System.out.println(ds);
System.out.println("DeleteSemantics.getDataset().getSourceList().getAliases()="+ds.getOptionList().get(0).getConditions().getConditionsList().get(0).getConditionsList().get(0).getConditionsList().get(1).getConditionList().get(1).getFuncList().get(1).getInput());
System.out.println("success");

//将class对象转化为jsonString
String jsonStr=gson.toJson(ds);
System.out.println(jsonStr);

//将json字符串变成json对象
JSONObject myJsonObject = null;
try {
myJsonObject = new JSONObject(jsonStr);
System.out.println(myJsonObject.get("dataset"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//java中的json对象可以使用put(key,value)进行添加,也可以使用get(key)提取对应的value----有点像map
try {
System.out.println(myJsonObject.get("dataset"));//因为dataset下还是json,则输出的还是json
System.out.println(myJsonObject.get("id"));//因为dataset下还是id,则输出的是string

String w = "{'name':'sff'}";
JSONObject jsonObj = new JSONObject(w);
jsonObj.put("age", "23");
myJsonObject.put("people", jsonObj);
System.out.println("myJsonObject:"+myJsonObject.get("people"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: