当前位置:首页 » 编程语言 » java取json

java取json

发布时间: 2024-02-24 14:17:17

1. java怎么得到json中的数据

如果不是Android开发环境的话,首先需要引入处理JSON数据的包:json-lib-2.2.3-jdk15.jar


Java样例程序如下:

importnet.sf.json.JSONArray;
importnet.sf.json.JSONObject;

publicclassDoJSON{
publicstaticvoidmain(String[]args){
JSONArrayemployees=newJSONArray(); //JSON数组
JSONObjectemployee=newJSONObject(); //JSON对象

employee.put("firstName","Bill"); //按“键-值”对形式存储数据到JSON对象中
employee.put("lastName","Gates");
employees.add(employee); //将JSON对象加入到JSON数组中

employee.put("firstName","George");
employee.put("lastName","Bush");
employees.add(employee);

employee.put("firstName","Thomas");
employee.put("lastName","Carter");
employees.add(employee);

System.out.println(employees.toString());
for(inti=0;i<employees.size();i++){
JSONObjectemp=employees.getJSONObject(i);
System.out.println(emp.toString());
System.out.println("FirstName: "+emp.get("firstName"));
System.out.println("LastName: "+emp.get("lastName"));
}
}
}


运行效果:

[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]

{"firstName":"Bill","lastName":"Gates"}

FirstName : Bill

LastName : Gates

{"firstName":"George","lastName":"Bush"}

FirstName : George

LastName : Bush

{"firstName":"Thomas","lastName":"Carter"}

FirstName : Thomas

LastName : Carter

2. 怎样从java后台获取json字符串并转换为json对象输出

使用json-lib.jar这个工具x0dx0apublic String getJson(Object obj){x0dx0a JSONObject json;x0dx0a json = JSONObject.fromObject(obj);x0dx0a return json.toString();x0dx0a}x0dx0a使用jquery来处理jsonx0dx0a//转换为json数据 datas可以用ajax从后台获取上面getJson中的数据x0dx0avar jsonDatas = eval("(" + datas + ")");x0dx0a //循环遍历数据x0dx0ajQuery.each(jsonDatas, function(item) {x0dx0a//循环x0dx0a});

3. java怎么取json数据的值

获取JSON的值。 就是解析JSON数据.

如果是简单的JSON数据, 并且只需要提取少量数据的值, 那么可以使用字符串的操作来实现,比如String.subString()...等

如果是比较复杂的JSON数据,或者需要提取的值比较多, 那么可以使用Gson, FastJSon 等第三方的jar来实现...

简单的Demo示例

第三方包使用的是Gson

importcom.google.gson.JsonElement;
importcom.google.gson.JsonObject;
importcom.google.gson.JsonParser;

publicclassGsonTest{
publicstaticvoidmain(String[]args){
StringstrJson="{"name":"张三","age":12}";
JsonParserparser=newJsonParser();
JsonElementje=parser.parse(strJson);
JsonObjectjobj=je.getAsJsonObject();//从json元素转变成json对象
Stringname=jobj.get("name").getAsString();//从json对象获取指定属性的值
System.out.println(name);
intage=jobj.get("age").getAsInt();
System.out.println(age);

}
}
热点内容
oraclesql序列 发布:2025-07-08 16:32:36 浏览:32
cod17编译着色器55 发布:2025-07-08 15:43:53 浏览:558
Shell脚本的posix模式 发布:2025-07-08 15:41:32 浏览:352
压缩奶油消泡 发布:2025-07-08 15:40:11 浏览:425
服务器一定要有公网ip吗 发布:2025-07-08 15:35:12 浏览:797
appendpython 发布:2025-07-08 15:22:54 浏览:656
安卓虚拟号码怎么设置 发布:2025-07-08 15:22:04 浏览:663
c语言爱心代码编译不出来 发布:2025-07-08 15:11:07 浏览:540
qq密码的数据库 发布:2025-07-08 14:54:50 浏览:6
多图床源码 发布:2025-07-08 14:46:36 浏览:573