java解析json字元串
java解析json格式文件,再保存在資料庫的方法:
1:定義一個實體類
2:用json lib將json字元串轉為Java對象
3:用jdbc或hibernate將java對象存入資料庫
直接讀寫文件,再把讀出來的文件內容格式化成json,再用JDBC、Mybatis或者其他框架將json數據存入資料庫。
假設實體類是這樣的:
publicclassElectSet{
publicStringxueqi;
publicStringxuenian;
publicStringstartTime;
publicStringendTime;
publicintmenshu;
publicStringisReadDB;
//{"xueqi":,"xuenian":,"startTime":,"endTime":,"renshu":,"isReadDB":}
publicStringgetXueqi(){
returnxueqi;
}
publicvoidsetXueqi(Stringxueqi){
this.xueqi=xueqi;
}
publicStringgetXuenian(){
returnxuenian;
}
publicvoidsetXuenian(Stringxuenian){
this.xuenian=xuenian;
}
publicStringgetStartTime(){
returnstartTime;
}
publicvoidsetStartTime(StringstartTime){
this.startTime=startTime;
}
publicStringgetEndTime(){
returnendTime;
}
publicvoidsetEndTime(StringendTime){
this.endTime=endTime;
}
publicintgetMenshu(){
returnmenshu;
}
publicvoidsetMenshu(intmenshu){
this.menshu=menshu;
}
publicStringgetIsReadDB(){
returnisReadDB;
}
publicvoidsetIsReadDB(StringisReadDB){
this.isReadDB=isReadDB;
}
}
有一個json格式的文件,存的信息如下:
Sets.json:
{"xuenian":"2007-2008","xueqi":"1","startTime":"2009-07-1908:30","endTime":"2009-07-2218:00","menshu":"10","isReadDB":"Y"}
具體操作:
/*
*取出文件內容,填充對象
*/
publicElectSetfindElectSet(Stringpath){
ElectSetelectset=newElectSet();
Stringsets=ReadFile(path);//獲得json文件的內容
JSONObjectjo=JSONObject.fromObject(sets);//格式化成json對象
//System.out.println("------------"jo);
//Stringname=jo.getString("xuenian");
//System.out.println(name);
electset.setXueqi(jo.getString("xueqi"));
electset.setXuenian(jo.getString("xuenian"));
electset.setStartTime(jo.getString("startTime"));
electset.setEndTime(jo.getString("endTime"));
electset.setMenshu(jo.getInt("menshu"));
electset.setIsReadDB(jo.getString("isReadDB"));
returnelectset;
}
//設置屬性,並保存
publicbooleansetElect(Stringpath,Stringsets){
try{
writeFile(path,sets);
returntrue;
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
returnfalse;
}
}
//讀文件,返回字元串
publicStringReadFile(Stringpath){
Filefile=newFile(path);
BufferedReaderreader=null;
Stringlaststr="";
try{
//System.out.println("以行為單位讀取文件內容,一次讀一整行:");
reader=newBufferedReader(newFileReader(file));
StringtempString=null;
intline=1;
//一次讀入一行,直到讀入null為文件結束
while((tempString=reader.readLine())!=null){
//顯示行號
System.out.println("line"line":"tempString);
laststr=laststrtempString;
line;
}
reader.close();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
}catch(IOExceptione1){
}
}
}
returnlaststr;
}
將獲取到的字元串,入庫即可。
2. Java中如何解析Json的字元串得到result、serialNumber的值
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
String json = "你的json";
JSONObject object = JSONObject.fromObject(json);
JSONObject alipay = object
.getJSONObject("者拿棚alipay_pass_sync_add_response");
JSONObject biz = alipay.getJSONObject("biz_result");
System.out.println(biz.get("result"敏枝));
System.out.println(biz.get("serialNumber"));
System.out.println(alipay.get("error_code"));
System.out.println(alipay.get("success"首則));
}
}
3. java解析json格式文件
/*簡單的回了復雜的也就會了*/
/*其實,json實際上是用來統一數據格式,所以,在使用它時,肯定要設計一下格式,
當然,所謂的復雜,只是嵌套的層次深了。。。解析方式並沒有變。。個人理解,如果覺得有價值就看,沒價值,就當沒看見吧。。
呵呵。。
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.sf.ezmorph.bean.MorphDynaBean;
import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
/**
* @author John
*
*/
public class JSONDemo {
public static final String PREFIX = "index_";
/**
* @param args
*/
public static void main(String[] args) {
Map map = new HashMap();
String str ="[{'status': 5,'remarks': '\\xe6\\xa3\\x80\\xe6\\xb5\\x8b\\xe5\\xb7\\xb2\\xe7\\xbb\\x8f\\xe5\\xae\\x8c\\xe6\\x88\\x90','session': \"(1, '9.2.0.1.0', '192.168.177.115', 1521L, 'ora9', 1, '')\",'vuls': [\"('612300200001', 1, '', [{'values': '['version']', 'type': 0}, {'values': \'['%E7%89%88%E6%9C%AC%E5%8F%B7']\', 'type': 1}])\",\"('612300200002', 1, '', [{'values': '['version']', 'type': 0},{'values': '['%E7%89%88%E6%9C%AC%E5%8F%B7']', 'type': 1},{'values': '['9.2.0.1.0']', 'type': 2}])\"], 'endTime':123}, 1L, '\\xe6\\xb5\\x8b\\xe8\\xaf\\x95\\xe6\\x89\\xab\\xe6\\x8f\\x8f\\xe4\\xbb\\xbb\\xe5\\x8a\\xa1']";
System.out.println("json格式字元串-->"+str);
JSONArray array = JSONArray.fromObject(str);
System.out.println("json格式字元串構造json數組元素的個數-->"+array.size());
ArrayList list = (ArrayList) JSONSerializer.toJava(array);
int i = 0;
for (Object obj : list) {
map.put(PREFIX+(i++), obj);
System.out.println("第"+i+"對象-->"+obj);
}
//解析第0個位置
Map bd = new HashMap();
MorphDynaBean bean = (MorphDynaBean) map.get(PREFIX+0);
bd.put("session", bean.get("session"));
bd.put("status", bean.get("status"));
bd.put("remarks", bean.get("remarks"));
bd.put("vuls", bean.get("vuls"));
bd.put("endTime", bean.get("endTime"));
Iterator iter = bd.keySet().iterator();
while (iter.hasNext()){
Object key = iter.next();
Object value = bd.get(key);
System.out.println("MorphDynaBean對象-->key="+key+",value="+value);
}
//解析vuls
ArrayList vuls = (ArrayList) bd.get("vuls");
Map vl = new HashMap();
int j = 0;
for (Object obj : vuls) {
vl.put(PREFIX+(j++), obj);
System.out.println("解析vuls的第"+i+"對象-->"+obj);
}
}
}
/*
* json格式字元串-->[{'status': 5,'remarks': '\xe6\xa3\x80\xe6\xb5\x8b\xe5\xb7\xb2\xe7\xbb\x8f\xe5\xae\x8c\xe6\x88\x90','session': "(1, '9.2.0.1.0', '192.168.177.115', 1521L, 'ora9', 1, '')",'vuls': ["('612300200001', 1, '', [{'values': '['version']', 'type': 0}, {'values': '['%E7%89%88%E6%9C%AC%E5%8F%B7']', 'type': 1}])","('612300200002', 1, '', [{'values': '['version']', 'type': 0},{'values': '['%E7%89%88%E6%9C%AC%E5%8F%B7']', 'type': 1},{'values': '['9.2.0.1.0']', 'type': 2}])"], 'endTime':123}, 1L, '\xe6\xb5\x8b\xe8\xaf\x95\xe6\x89\xab\xe6\x8f\x8f\xe4\xbb\xbb\xe5\x8a\xa1']
json格式字元串構造json數組元素的個數-->3
第1對象-->net.sf.ezmorph.bean.MorphDynaBean@94948a[
{session=(1, '9.2.0.1.0', '192.168.177.115', 1521L, 'ora9', 1, ''), status=5, remarks=???????·??????????, vuls=[('612300200001', 1, '', [{'values': '['version']', 'type': 0}, {'values': '['%E7%89%88%E6%9C%AC%E5%8F%B7']', 'type': 1}]), ('612300200002', 1, '', [{'values': '['version']', 'type': 0},{'values': '['%E7%89%88%E6%9C%AC%E5%8F%B7']', 'type': 1},{'values': '['9.2.0.1.0']', 'type': 2}])], endTime=123}
]
第2對象-->1L
第3對象-->???è??????????????
MorphDynaBean對象-->key=status,value=5
MorphDynaBean對象-->key=session,value=(1, '9.2.0.1.0', '192.168.177.115', 1521L, 'ora9', 1, '')
MorphDynaBean對象-->key=remarks,value=???????·??????????
MorphDynaBean對象-->key=vuls,value=[('612300200001', 1, '', [{'values': '['version']', 'type': 0}, {'values': '['%E7%89%88%E6%9C%AC%E5%8F%B7']', 'type': 1}]), ('612300200002', 1, '', [{'values': '['version']', 'type': 0},{'values': '['%E7%89%88%E6%9C%AC%E5%8F%B7']', 'type': 1},{'values': '['9.2.0.1.0']', 'type': 2}])]
MorphDynaBean對象-->key=endTime,value=123
解析vuls的第3對象-->('612300200001', 1, '', [{'values': '['version']', 'type': 0}, {'values': '['%E7%89%88%E6%9C%AC%E5%8F%B7']', 'type': 1}])
解析vuls的第3對象-->('612300200002', 1, '', [{'values': '['version']', 'type': 0},{'values': '['%E7%89%88%E6%9C%AC%E5%8F%B7']', 'type': 1},{'values': '['9.2.0.1.0']', 'type': 2}])
*/
4. java 解析json字元串
你好:
後台拆分json
privateStringinteractPrizeAll;//json使用字元串來接收
方法中的代碼:
Gsongson=newGson();
InteractPrizeinteractPrize=newInteractPrize();
//gson用泛型轉List數組多個對象
List<InteractPrize>interactPrizeList=gson.fromJson(interactPrizeAll,newTypeToken<List<InteractPrize>>(){}.getType());//TypeToken,它是gson提供的數據類型轉換器,可以支持各種數據集合類型轉換
for(inti=0;i<interactPrizeList.size();i++)
{
interactPrize=interactPrizeList.get(i);//獲取每一個對象
}
這一種方法是轉單個對象時使用的
//gson轉對象單個對象
//interactPrize=gson.fromJso(interactPrizeAll,InteractPrize.class);
這個方法是我後台拼的json往前台傳的方法
jsonStrAll.append("{"+"""+"catid"+"""+":"+"""+c.getCatid()+"""+","+"""+"catname"+"""+":"+"""+c.getCatname()+"""+","+"""+"catdesc"+"""+":"+"""+c.getCatdesc()+"""+","+"""+"showinnav"+"""+":"+"""+c.getShowinnav()+"""+","+"""+"sortorder"+"""+":"+"""+c.getSortorder()+"""+","+"level:"+"""+"0"+"""+",parent:"+"""+"0"+"""+",isLeaf:true,expanded:false,"+"loaded:true},");
你自己挑著用吧!
5. java 解析json字元串格式 [{}]
你在哪裡解析
1、Java類裡面:JSONObject jsonObject = new JSONObject(str);
然後用Iterator迭代器遍並滲知歷取值,建議用反射機制解析到封裝好的對象中
2、javascript:JSON.parse(str);
ie8(兼容模式),ie7和ie6沒有JSON對象,不過http://www.json.org/提供了一個json.js,這樣ie8(兼容模式),ie7和ie6就可以支持JSON對象以及其stringify()和parse()方法;你可以在https://github.com/douglascrockford/JSON-js上獲取到這個js,一般現在用json2.js。
ie8(兼容模式),ie7和ie6可以使用eval()將字元串轉為JSON對絕消象,
var c='{"name":"Mike","sex":"女","age":"29"}'喊卜;
var cToObj=eval("("+str+")");
6. 怎樣用java解析一個json字元串
public static void main(String[] args){
String temp="{'data':{'a':[{'b1':'bb1','c1':'cc1'},{'b2':'bb2','c2':'cc2'}]}}";
JSONObject jodata =JSONObject.fromObject(temp);
JSONObject joa =JSONObject.fromObject(jodata.get("data").toString());
JSONArray ja=JSONArray.fromObject(joa.get("a"));
for(int i=0;i<ja.size();i++){
JSONObject o=ja.getJSONObject(i);
if(o.get("b1")!=null){
System.out.println(o.get("b1"));
}
if(o.get("c1")!=null){
System.out.println(o.get("c1"));
}
if(o.get("b2")!=null){
System.out.println(o.get("b2"));
}
if(o.get("c2")!=null){
System.out.println(o.get("c2"));
}
}
}
註:要包含兩個jar包ezmorph-1.0.6.jar和json-lib-2.2.2-jdk15.jar,jar包在附件中
7. java解析json字元串 放到數組中
java解析json字元串時將大括弧中的對應為一個類,裡面的數據對應為類的屬性,最後用數組接受即可。
示例關鍵代碼如下:
//導入net.sf.json.JSONArray和net.sf.json.JSONObject兩個jar包
Stringstr="[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]";//一個未轉化的字元串
JSONArrayjson=JSONArray.fromObject(str);//首先把字元串轉成JSONArray對象
if(json.size()>0){
for(inti=0;i<json.size();i++){
JSONObjectjob=json.getJSONObject(i);//遍歷jsonarray數組,把每一個對象轉成json對象
System.out.println(job.get("name")+"=");//得到每個對象中的屬性值
}
}
8. java後台解析json字元串
JSONArray 是json數據格式,它下邊包含了jsonObject格式,所以你應該先取jsonObject,如:
for(int z = 0; z < leng; z++){
System.out.println("zzzz"+z);
JSONObject json = jsona.getJSONObject(z);
String name = json.get("name").toString;
}
你的jsonarray格式要是正確的話就應該可以拿到name值。
9. java 怎麼解析jsonp字元串
public static void main(String[] args){
String temp="{'data':{'a':[{'b1':'bb1','c1':'cc1'},{'b2':'bb2','c2':'cc2'}]}}";
JSONObject jodata =JSONObject.fromObject(temp);
JSONObject joa =JSONObject.fromObject(jodata.get("data").toString());
JSONArray ja=JSONArray.fromObject(joa.get("a"));
for(int i=0;i<游梁數ja.size();i++){
JSONObject o=ja.getJSONObject(i);
if(o.get("b1")!=null){
System.out.println(o.get("b1"));
}
if(o.get("c1")!=null){
System.out.println(o.get("c1"));
}
if(o.get("b2")!=null){
System.out.println(o.get("b2"));
}
if(o.get("c2")!=null){
System.out.println(o.get("c2"));
}
}
}
注渣稿:要包含兩個jar包ezmorph-1.0.6.jar和神首json-lib-2.2.2-jdk15.jar,jar包在附件中
10. 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如何定義.剩下的就非常簡單了.