本文目录一览:
java怎么处理json格式数据
1、通过谷歌的Gson来进行解析:
json数据:sTotalString = {"message":"success","result":[{"surveyid":"1","surveyname":"B"}{surveyid":"2","surveyname":"C"}]};
2、通过json-org.jar包进行解析:
json数据:sTotalString = {"message":"success","result":[{"surveyid":"1","surveyname":"B"}{surveyid":"2","surveyname":"C"}]};
java解析json格式文件,再保存在数据库怎么做?
java解析json格式文件,再保存在数据库的方法:
1:定义一个实体类
2:用json lib将json字符串转为Java对象
3:用jdbc或hibernate将java对象存入数据库
直接读写文件,再把读出来的文件内容格式化成json,再用JDBC、Mybatis或者其他框架将json数据存入数据库。
假设实体类是这样的:
public class ElectSet {
public String xueqi;
public String xuenian;
public String startTime;
public String endTime;
public int menshu;
public String isReadDB;
//{"xueqi":,"xuenian":,"startTime":,"endTime":,"renshu":,"isReadDB":}
public String getXueqi() {
return xueqi;
}
public void setXueqi(String xueqi) {
this.xueqi = xueqi;
}
public String getXuenian() {
return xuenian;
}
public void setXuenian(String xuenian) {
this.xuenian = xuenian;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public int getMenshu() {
return menshu;
}
public void setMenshu(int menshu) {
this.menshu = menshu;
}
public String getIsReadDB() {
return isReadDB;
}
public void setIsReadDB(String isReadDB) {
this.isReadDB = isReadDB;
}
}
有一个json格式的文件,存的信息如下:
Sets.json:
{"xuenian":"2007-2008","xueqi":"1","startTime":"2009-07-19 08:30","endTime":"2009-07-22 18:00","menshu":"10","isReadDB":"Y"}
具体操作:
/*
* 取出文件内容,填充对象
*/
public ElectSet findElectSet(String path){
ElectSet electset=new ElectSet();
String sets=ReadFile(path);//获得json文件的内容
JSONObject jo=JSONObject.fromObject(sets);//格式化成json对象
//System.out.println("------------" jo);
//String name = 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"));
return electset;
}
//设置属性,并保存
public boolean setElect(String path,String sets){
try {
writeFile(path,sets);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
//读文件,返回字符串
public String ReadFile(String path){
File file = new File(path);
BufferedReader reader = null;
String laststr = "";
try {
//System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
//一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
//显示行号
System.out.println("line " line ": " tempString);
laststr = laststr tempString;
line ;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return laststr;
}
将获取到的字符串,入库即可。
java 如何解析JSON
一、JSON(JavaScriptObjectNotation)一种简单的数据格式,比xml更轻巧。Json建构于两种结构:1、“名称/值”对的集合(Acollectionofname/valuepairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hashtable),有键列表(keyedlist),或者关联数组(associativearray)。如:{“name”:”jackson”,“age”:100}2、值的有序列表(Anorderedlistofvalues)。在大部分语言中,它被理解为数组(array)如:{“students”:[{“name”:”jackson”,“age”:100},{“name”:”michael”,”age”:51}]}二、java解析JSON步骤A、服务器端将数据转换成json字符串首先、服务器端项目要导入json的jar包和json所依赖的jar包至builtPath路径下(这些可以到JSON-lib官网下载:)然后将数据转为json字符串,核心函数是:publicstaticStringcreateJsonString(Stringkey,Objectvalue){JSONObjectjsonObject=newJSONObject();jsonObject.put(key,value);returnjsonObject.toString();}B、客户端将json字符串转换为相应的javaBean1、客户端获取json字符串(因为android项目中已经集成了json的jar包所以这里无需导入)publicclassHttpUtil{publicstaticStringgetJsonContent(StringurlStr){try{//获取HttpURLConnection连接对象URLurl=newURL(urlStr);HttpURLConnectionhttpConn=(HttpURLConnection)url.openConnection();//设置连接属性httpConn.setConnectTimeout(3000);httpConn.setDoInput(true);httpConn.setRequestMethod("GET");//获取相应码intrespCode=httpConn.getResponseCode();if(respCode==200){returnConvertStream2Json(httpConn.getInputStream());}}catch(MalformedURLExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}return"";}privatestaticStringConvertStream2Json(InputStreaminputStream){StringjsonStr="";//ByteArrayOutputStream相当于内存输出流ByteArrayOutputStreamout=newByteArrayOutputStream();byte[]buffer=newbyte[1024];intlen=0;//将输入流转移到内存输出流中try{while((len=inputStream.read(buffer,0,buffer.length))!=-1){out.write(buffer,0,len);}//将内存流转换为字符串jsonStr=newString(out.toByteArray());}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}returnjsonStr;}}2、获取javaBeanpublicstaticPersongetPerson(StringjsonStr){Personperson=newPerson();try{//将json字符串转换为json对象JSONObjectjsonObj=newJSONObject(jsonStr);//得到指定jsonkey对象的value对象JSONObjectpersonObj=jsonObj.getJSONObject("person");//获取之对象的所有属性person.setId(personObj.getInt("id"));person.setName(personObj.getString("name"));person.setAddress(personObj.getString("address"));}catch(JSONExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}returnperson;}publicstaticListgetPersons(StringjsonStr){Listlist=newArrayList();JSONObjectjsonObj;try{//将json字符串转换为json对象jsonObj=newJSONObject(jsonStr);//得到指定jsonkey对象的value对象JSONArraypersonList=jsonObj.getJSONArray("persons");//遍历jsonArrayfor(inti=0;i
java中Json怎样解析数据?
你这个JSON格式,就是数组里面放数组,所以是,取JSON对象》取JSON数组data》取JSON数组。
import java.util.ArrayList;import java.util.Iterator;import net.sf.json.*;public class MainClass {/*** @param args*/public static void main(String[] args) {JSONObject jsonObj = JSONObject.fromObject(JsonData.getData());JSONArray jsonArr = jsonObj.getJSONArray("data");IteratorJSONArray itr = jsonArr.iterator();JSONArray temp;while(itr.hasNext()) {temp = itr.next();System.out.println("===========Each JSONArray=========");for(int i = 0; itemp.size(); i++) {System.out.println(temp.get(i));}}}private static class JsonData {private static String getData() {return "{\"data\":[[5000235,2,3441,8,17,\"北京测试\",\"10000101111\",\"\",\"\",\"100001\",\"\",\"2011-09-23 17:20:07\",18,\"vhcDefaultPwd\",1,0,\"2011-09-20 00:00:00\",12,0,380,\"测试\",213,1,0,0,0,0,0,\"2012-11-05 14:35:23\",\"\"],[5000236,27,3442,10,17,\"北京测试2\",\"1230000\",\"\",\"\",\"2010920002\",\"111111\",\"2011-09-23 17:20:08\",18,\"vhcDefaultPwd\",1,0,\"2011-09-20 00:00:00\",12,0,380,\"测试2\",213,1,0,0,0,0,0,\"2012-11-05 14:35:23\",\"\"]]}";}}}
java 解析json字符串
你好:
后台拆分json
private String interactPrizeAll; //json 使用字符串来接收
方法中的代码:
Gson gson = new Gson();
InteractPrize interactPrize =new InteractPrize();
//gson用泛型 转List数组 多个对象
ListInteractPrize interactPrizeList = gson.fromJson(interactPrizeAll, new TypeTokenListInteractPrize(){}.getType()); //TypeToken,它是gson提供的数据类型转换器,可以支持各种数据集合类型转换
for(int i = 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},");
你自己挑着用吧!