㈠ 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);
}