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如何定义.剩下的就非常简单了.