㈠ java jSon实例编写
是这么个过程
1、在页面用js发出个ajax请求,请求类型最好写成json,建议使用jquery的ajax方法,省事。请求的路径要配在web.xml中
2、这个请求路径制定的是一个servlet,就是一个java类,继承自httpservlet。这个servlet里可以通过request对象获取到输入参数,根据输入参数和自己具体的逻辑拼出个字符串,当然是json格式的。然后输出。这个不会写说明你需要补一补java web开发的基础知识。
3、在页面的ajax请求的success方法中,直接可以获取到返回的json对象,然后就根据你的json格式处理吧。
$.ajax({
url: 'ajax/test',//这个是servlet请求路径
success: function(data) { //data就是servlet输出的json格式字符串,这里会自动转化为json对象
alert('Load was performed.');
}
});
㈡ java中json怎么运用
json一般都是配合ajax一起使用的 我做做过的小例子 粘给你 你可以研究一下
js部分
//获取卡的金额
function get_money(){
var str=document.getElementById("pk_card_type").value;
//alert(str);
var url = '/member_h.do';
var pars = 'method=getMoney';
pars+='&pk_card_type='+str;
var ajax = new Ajax.Request(
url,
{method:'post',parameters:pars,onComplete:show_money}
);
}
//回调函数 写入卡的金额
function show_money(dataResponse)
{
var data = eval('(' + dataResponse.responseText + ')');
var price=0;
price=data.price;
var collection_fees=0;
collection_fees=data.collection_fees;
document.getElementById("recharge").value=price;
document.getElementById("collection_fees").value=collection_fees;
}
action部分
public ActionForward getMoney(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html; charset=utf-8");
try {
IElementaryFileService ggsv = new ElementaryFileService();
String pk_card_type = request.getParameter("pk_card_type");
Card_TypeVO ctvo=new Card_TypeVO();
ctvo=ggsv.queryByPK(Card_TypeVO.class, pk_card_type);
PrintWriter out = response.getWriter();
// 这里的数据拼装一般是从数据库查询来的
JSONObject jsonObject = new JSONObject();
if(ctvo!=null){
jsonObject.put("price", ctvo.getCard_money());
jsonObject.put("collection_fees", ctvo.getCash());
}else{
jsonObject.put("price", 0);
jsonObject.put("collection_fees", 0);
}
out.print(jsonObject.toString());
out.flush();
out.close();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
㈢ java怎么使用gson解析json字符串
Gson是谷歌推出的解析json数据以及将对象转换成json数据的一个开源框架. 现在json因其易读性和高效率而被广泛的使用着.
相对于java以及其它json的解析框架,Gson非常的好用.
简单来讲就是根据json的数据结构定义出相应的javabean --->"new"出Gson的实例gson---->gson.fromJson(jsonString,JavaBean.class) 即可.
下面给出一个实例来说明.
步骤1:目标:将从webservice传回的json
{
"status":0,
"result":{
"location":{
"lng":103.98964143811,
"lat":30.586643130352
},
"formatted_address":"四川省成都市双流县北一街154",
"business":"簇桥,金花桥",
"addressComponent":{
"city":"成都市",
"district":"双流县",
"province":"四川省",
"street":"北一街",
"street_number":"154"
},
"cityCode":75
}
}
先普及下json数据格式定义: json数据只有两种格式.
一种是对象: 一个大括号包裹的内容就是一个对象.里面是无数个逗号相间隔的键值对
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
一种是数组:一个方括号包裹的内容就是一个数组,里面是无数个逗号相间隔的json对象
如:
{
"people":[
{
"firstName":"Brett",
"lastName":"McLaughlin",
"email":"aaaa"
},
{
"firstName":"Jason",
"lastName":"Hunter",
"email":"bbbb"
},
{
"firstName":"Elliotte",
"lastName":"Harold",
"email":"cccc"
}
]
}
步骤2 定义json数据格式对应的javaBean
publicclassResult{
privateIntegerstatus;
privateResultDetailresult;
publicResult(){
}
publicResult(Integerstatus,ResultDetailresult){
super();
this.status=status;
this.result=result;
}
publicResultDetailgetResult(){
returnthis.result;
}
publicIntegergetStatus(){
returnthis.status;
}
publicvoidsetResult(ResultDetailresult){
this.result=result;
}
publicvoidsetStatus(Integerstatus){
this.status=status;
}
@Override
publicStringtoString(){
return"Result[status="+this.status+",result="+this.result
+"]";
}
}
publicclassResultDetail{
Locationlocation;
Stringformatted_address;
;
Stringbusiness;
StringcityCode;
publicResultDetail(){
super();
//TODOAuto-generatedconstructorstub
}
publicResultDetail(Locationlocation,Stringformatted_address,
,Stringbusiness,StringcityCode){
super();
this.location=location;
this.formatted_address=formatted_address;
this.addressComponent=addressComponent;
this.business=business;
this.cityCode=cityCode;
}
(){
returnthis.addressComponent;
}
publicStringgetBusiness(){
returnthis.business;
}
publicStringgetCityCode(){
returnthis.cityCode;
}
publicStringgetFormatted_address(){
returnthis.formatted_address;
}
publicLocationgetLocation(){
returnthis.location;
}
publicvoidsetAddressComponent(){
this.addressComponent=addressComponent;
}
publicvoidsetBusiness(Stringbusiness){
this.business=business;
}
publicvoidsetCityCode(StringcityCode){
this.cityCode=cityCode;
}
publicvoidsetFormatted_address(Stringformatted_address){
this.formatted_address=formatted_address;
}
publicvoidsetLocation(Locationlocation){
this.location=location;
}
}
publicclassLocation{
Stringlng;
Stringlat;
publicLocation(){
}
publicLocation(Stringlng,Stringlat){
this.lng=lng;
this.lat=lat;
}
publicStringgetLat(){
returnthis.lat;
}
publicStringgetLng(){
returnthis.lng;
}
publicvoidsetLat(Stringlat){
this.lat=lat;
}
publicvoidsetLng(Stringlng){
this.lng=lng;
}
@Override
publicStringtoString(){
return"Location[lng="+this.lng+",lat="+this.lat+"]";
}
}
publicclassAddressComponent{
Stringcity;
Stringdistrict;
Stringprovince;
Stringstreet;
Stringstreet_number;
publicAddressComponent(){
super();
//TODOAuto-generatedconstructorstub
}
publicAddressComponent(Stringcity,Stringdistrict,Stringprovince,
Stringstreet,Stringstreet_number){
super();
this.city=city;
this.district=district;
this.province=province;
this.street=street;
this.street_number=street_number;
}
publicStringgetCity(){
returnthis.city;
}
publicStringgetDistrict(){
returnthis.district;
}
publicStringgetProvince(){
returnthis.province;
}
publicStringgetStreet(){
returnthis.street;
}
publicStringgetStreet_number(){
returnthis.street_number;
}
publicvoidsetCity(Stringcity){
this.city=city;
}
publicvoidsetDistrict(Stringdistrict){
this.district=district;
}
publicvoidsetProvince(Stringprovince){
this.province=province;
}
publicvoidsetStreet(Stringstreet){
this.street=street;
}
publicvoidsetStreet_number(Stringstreet_number){
this.street_number=street_number;
}
@Override
publicStringtoString(){
return"AddressComponent[city="+this.city+",district="
+this.district+",province="+this.province+",street="
+this.street+",street_number="+this.street_number+"]";
}
}
测试:
jsonString ( 目标json数据,已经在最上面写好的)
System.out.println("jsonString:"+jsonString);
Gsongson=newGson();
ResultfromJson=gson.fromJson(jsonString.toString(),Result.class);
System.out.println("******************************************");
System.out.println(fromJson);
结果:
jsonString:{"status":0,"result":{"location":{"lng":103.98964143811,"lat":30.586643130352},"formatted_address":"四川省成都市双流县北一街154","business":"簇桥,金花桥","addressComponent":{"city":"成都市","district":"双流县","province":"四川省","street":"北一街","street_number":"154"},"cityCode":75}}
*******************************************
Result[status=0,result=ResultDetail[location=Location[lng=103.98964143811,lat=30.586643130352],formatted_address=四川省成都市双流县北一街154,addressComponent=AddressComponent[city=成都市,district=双流县,province=四川省,street=北一街,street_number=154],business=簇桥,金花桥,cityCode=75]]
可见,jsonString已经成功的被转换成了对应的javaBean
步骤3 : 总结.说明
Gson可以很轻松的实现javaBean和jsonString之间的互转.只需要明白json如何定义.剩下的就非常简单了.
㈣ java 怎么将List<List<Object>>类型转换成json类型,怎么读取json类型
java中将list对象转换成json类型,可以使用json拼接的方式,实例如下:
json:[{},{}]
Stringjson="[";
for(Objectobj:list){
json=json+"{"+obj+"}";
}
json=json+"]"
returnjson;
㈤ java中AJAX使用JSON的实例
我空间有一个例子:用Ajax实现多级联动下拉列表For JSP,地址:http://hi..com/tz666/blog/item/63f17ca342eb81b8cbefd019.html
㈥ 有没有将json直接转换生成Java类的工具软件
使用Jackson可以将json转为Java对象,同样也可以将java对象转为json字符串,并且Spring框架内部也是使用的此jar。
实例:将json转为java对象
/*
下面的id,name,age同是User实体类的属性
*/
//将json转为Java对象
Stringjson="{"id":1,"name":"张三","age":18}";
ObjectMappermapper=newObjectMapper();
Useruser=mapper.readValue(json,User.class);、
//将json转为Java数组对象
Stringjson="[{"id":1,"name":"张三","age":18},{"id":2,"name":"李四","age":18},{"id":3,"name":"王五","age":18}]";
ObjectMappermapper=newObjectMapper();
User[]users=mapper.readValue(json,User[].class);
㈦ JAVA如何获取json字符串 最好有实例 感谢
//bean类
publicclassTet{
privateStringbuildingNum;//"E1",
privateStringclassName;//"1",
privateStringclassNum;//"通信15-1班",
privateStringcollege;//"电子信息工程学院",
privateStringdormNum;//"110",
privateStringgrade;//"2015",
privateStringisCommunist;//"0",
privateStringisDormLeader;//"1",
privateStringisStudentLeader;//"1",
privateStringmajor;//"通信工程",
privateStringphoneNum;//"13591991111",
privateStringstatus;//"1",
privateStringstudentId;//"1",
privateStringstudentName;//"张三",
privateStringteachername;//"张四"
publicStringgetBuildingNum(){
returnbuildingNum;
}
publicvoidsetBuildingNum(StringbuildingNum){
this.buildingNum=buildingNum;
}
publicStringgetClassName(){
returnclassName;
}
publicvoidsetClassName(StringclassName){
this.className=className;
}
publicStringgetClassNum(){
returnclassNum;
}
publicvoidsetClassNum(StringclassNum){
this.classNum=classNum;
}
publicStringgetCollege(){
returncollege;
}
publicvoidsetCollege(Stringcollege){
this.college=college;
}
publicStringgetDormNum(){
returndormNum;
}
publicvoidsetDormNum(StringdormNum){
this.dormNum=dormNum;
}
publicStringgetGrade(){
returngrade;
}
publicvoidsetGrade(Stringgrade){
this.grade=grade;
}
publicStringgetIsCommunist(){
returnisCommunist;
}
publicvoidsetIsCommunist(StringisCommunist){
this.isCommunist=isCommunist;
}
publicStringgetIsDormLeader(){
returnisDormLeader;
}
publicvoidsetIsDormLeader(StringisDormLeader){
this.isDormLeader=isDormLeader;
}
(){
returnisStudentLeader;
}
publicvoidsetIsStudentLeader(StringisStudentLeader){
this.isStudentLeader=isStudentLeader;
}
publicStringgetMajor(){
returnmajor;
}
publicvoidsetMajor(Stringmajor){
this.major=major;
}
publicStringgetPhoneNum(){
returnphoneNum;
}
publicvoidsetPhoneNum(StringphoneNum){
this.phoneNum=phoneNum;
}
publicStringgetStatus(){
returnstatus;
}
publicvoidsetStatus(Stringstatus){
this.status=status;
}
publicStringgetStudentId(){
returnstudentId;
}
publicvoidsetStudentId(StringstudentId){
this.studentId=studentId;
}
publicStringgetStudentName(){
returnstudentName;
}
publicvoidsetStudentName(StringstudentName){
this.studentName=studentName;
}
publicStringgetTeachername(){
returnteachername;
}
publicvoidsetTeachername(Stringteachername){
this.teachername=teachername;
}
}
//实现类
importnet.sf.json.JSONArray;
publicclassTest{
publicstaticvoidmain(String[]args){
/*
*做法建立一个bean类属性就为字符串的Key;
*/
//定义JSON串String类型
Stringa="[{"buildingNum":"E1","className":"1","classNum":"通信15-1班","college":"电子信息工程学院","dormNum":"110","grade":"2015","isCommunist":"0","isDormLeader":"1","isStudentLeader":"1","major":"通信工程","phoneNum":"13591991111","status":"1","studentId":"1","studentName":"张三","teachername":"张四"},{"buildingNum":"E1","className":"1","classNum":"通信15-1班","college":"电子信息工程学院","dormNum":"110","grade":"2015","isCommunist":"0","isDormLeader":"1","isStudentLeader":"1","major":"通信工程","phoneNum":"13591991111","status":"1","studentId":"2","studentName":"张1","teachername":"张四"},{"buildingNum":"E1","className":"1","classNum":"通信15-1班","college":"电子信息工程学院","dormNum":"110","grade":"2015","isCommunist":"0","isDormLeader":"1","isStudentLeader":"1","major":"通信工程","phoneNum":"13591991111","status":"1","studentId":"3","studentName":"张2","teachername":"张四"},{"buildingNum":"E1","className":"1","classNum":"通信15-1班","college":"电子信息工程学院","dormNum":"101","grade":"2015","isCommunist":"0","isDormLeader":"1","isStudentLeader":"1","major":"通信工程","phoneNum":"13591991111","status":"1","studentId":"4","
+""studentName":"张3","teachername":"张四"}]";
//转换成集合
List<Tet>list2=(List<Tet>)JSONArray.toList(JSONArray.fromObject(a),Tet.class);
for(Tett:list2){
//取出编号
System.out.println(t.getBuildingNum());
}
//转换成数组
Tet[]ss=(Tet[])JSONArray.toArray(JSONArray.fromObject(a),Tet.class);
for(Tett:ss){
//取出姓名
System.out.println(t.getTeachername());
}
}
}
㈧ Java实现JSON多层遍历
JSONObject jsonObject = new JSONObject(s);
然后用Iterator迭代器遍历取值,建议用反射机制解析到封装好的对象中
JSONObject jsonObject = new JSONObject(jsonString);
Iterator iterator = jsonObject.keys();while(iterator.hasNext()){
key = (String) iterator.next();
value = jsonObject.getString(key);
}