㈠ java開發,json是干什麼的
json其實就是封裝了一種數據格式,它使用了自己定義的標准。主要用來在伺服器和客戶端的瀏覽器進行數據交換。因為我們常用的表單形式提交數據,有諸多的不便,json解決了一些問題。
㈡ java怎麼讀取json格式的數據
java可以使用JSONObject和JSONArray來操作json對象和json數組,具體用法如下
1:java對象與json串轉換:
java對象—json串:
JSONObject JSONStr = JSONObject.fromObject(object);
String str = JSONStr.toString();
json串—java對象:
JSONObject jsonObject = JSONObject.fromObject( jsonString );
Object pojo = JSONObject.toBean(jsonObject,pojoCalss);
2:java數組對象與json串轉換:
java數組—json串:
JSONArray arrayStr = JSONArray.fromObject(List<?>);
String str = arrayStr.toString();
json串—java數組:
JSONArray array = JSONArray.fromObject(str);
List<?> list = JSONArray.toList(array, ?.class);
㈢ Java中哪個JSON庫的解析速度是最快的
FastJson效率最高,是阿里巴巴開源 的Json處理工具包,包括「序列化」和「反序列化」兩部分,它具備如下特徵:
速度最快,測試表明,空氏猛fastjson具有極快的性能,超斗橋越任其他的Java Json parser。包括自稱最快的JackJson;
功核態能強大,完全支持Java Bean、集合、Map、日期、Enum,支持范型,支持自省;無依賴,能夠直接運行在Java SE 5.0以上版本;支持android;
㈣ java解析json字元串數據
這個需要導入個jar包的,自己寫太麻煩,而且要考慮特殊字元的轉義的。
1. json-lib是一個java類庫,提供將Java對象,包括beans, maps, collections, java arrays and XML等轉換成JSON,或者反向轉換的功能。
2. json-lib 主頁 :http://json-lib.sourceforge.net/
3.執行環境
需要以下類庫支持
jakarta commons-lang 2.5
jakarta commons-beanutils 1.8.0
jakarta commons-collections 3.2.1
jakarta commons-logging 1.1.1
ezmorph 1.0.6
4.功能示例
這里通過JUnit-Case例子給出代碼示例
packagecom.mai.json;
importstaticorg.junit.Assert.assertEquals;
importjava.util.ArrayList;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importnet.sf.ezmorph.Morpher;
importnet.sf.ezmorph.MorpherRegistry;
importnet.sf.ezmorph.bean.BeanMorpher;
importnet.sf.json.JSONArray;
importnet.sf.json.JSONObject;
importnet.sf.json.util.JSONUtils;
importorg.apache.commons.beanutils.PropertyUtils;
importorg.junit.Test;
publicclassJsonLibTest{
/*
*普通類型、List、Collection等都是用JSONArray解析
*
*Map、自定義類型是用JSONObject解析
*可以將Map理解成一個對象,裡面的key/value對可以理解成對象的屬性/屬性值
*即{key1:value1,key2,value2......}
*
*1.JSONObject是一個name:values集合,通過它的get(key)方法取得的是key後對應的value部分(字元串)
*通過它的getJSONObject(key)可以取到一個JSONObject,-->轉換成map,
*通過它的getJSONArray(key)可以取到一個JSONArray,
*
*
*/
//一般數組轉換成JSON
@Test
publicvoidtestArrayToJSON(){
boolean[]boolArray=newboolean[]{true,false,true};
JSONArrayjsonArray=JSONArray.fromObject(boolArray);
System.out.println(jsonArray);
//prints[true,false,true]
}
//Collection對象轉換成JSON
@Test
publicvoidtestListToJSON(){
Listlist=newArrayList();
list.add("first");
list.add("second");
JSONArrayjsonArray=JSONArray.fromObject(list);
System.out.println(jsonArray);
//prints["first","second"]
}
//字元串json轉換成json,根據情況是用JSONArray或JSONObject
@Test
publicvoidtestJsonStrToJSON(){
JSONArrayjsonArray=JSONArray.fromObject("['json','is','easy']");
System.out.println(jsonArray);
//prints["json","is","easy"]
}
//Map轉換成json,是用jsonObject
@Test
publicvoidtestMapToJSON(){
Mapmap=newHashMap();
map.put("name","json");
map.put("bool",Boolean.TRUE);
map.put("int",newInteger(1));
map.put("arr",newString[]{"a","b"});
map.put("func","function(i){returnthis.arr[i];}");
JSONObjectjsonObject=JSONObject.fromObject(map);
System.out.println(jsonObject);
}
//復合類型bean轉成成json
@Test
publicvoidtestBeadToJSON(){
MyBeanbean=newMyBean();
bean.setId("001");
bean.setName("銀行卡");
bean.setDate(newDate());
ListcardNum=newArrayList();
cardNum.add("農行");
cardNum.add("工行");
cardNum.add("建行");
cardNum.add(newPerson("test"));
bean.setCardNum(cardNum);
JSONObjectjsonObject=JSONObject.fromObject(bean);
System.out.println(jsonObject);
}
//普通類型的json轉換成對象
@Test
publicvoidtestJSONToObject()throwsException{
Stringjson="{name="json",bool:true,int:1,double:2.2,func:function(a){returna;},array:[1,2]}";
JSONObjectjsonObject=JSONObject.fromObject(json);
System.out.println(jsonObject);
Objectbean=JSONObject.toBean(jsonObject);
assertEquals(jsonObject.get("name"),PropertyUtils.getProperty(bean,"name"));
assertEquals(jsonObject.get("bool"),PropertyUtils.getProperty(bean,"bool"));
assertEquals(jsonObject.get("int"),PropertyUtils.getProperty(bean,"int"));
assertEquals(jsonObject.get("double"),PropertyUtils.getProperty(bean,"double"));
assertEquals(jsonObject.get("func"),PropertyUtils.getProperty(bean,"func"));
System.out.println(PropertyUtils.getProperty(bean,"name"));
System.out.println(PropertyUtils.getProperty(bean,"bool"));
System.out.println(PropertyUtils.getProperty(bean,"int"));
System.out.println(PropertyUtils.getProperty(bean,"double"));
System.out.println(PropertyUtils.getProperty(bean,"func"));
System.out.println(PropertyUtils.getProperty(bean,"array"));
ListarrayList=(List)JSONArray.toCollection(jsonObject.getJSONArray("array"));
for(Objectobject:arrayList){
System.out.println(object);
}
}
//將json解析成復合類型對象,包含List
@Test
(){
Stringjson="{list:[{name:'test1'},{name:'test2'}],map:{test1:{name:'test1'},test2:{name:'test2'}}}";
//Stringjson="{list:[{name:'test1'},{name:'test2'}]}";
MapclassMap=newHashMap();
classMap.put("list",Person.class);
MyBeanWithPersondiyBean=(MyBeanWithPerson)JSONObject.toBean(JSONObject.fromObject(json),MyBeanWithPerson.class,classMap);
System.out.println(diyBean);
Listlist=diyBean.getList();
for(Objecto:list){
if(oinstanceofPerson){
Personp=(Person)o;
System.out.println(p.getName());
}
}
}
//將json解析成復合類型對象,包含Map
@Test
(){
//把Map看成一個對象
Stringjson="{list:[{name:'test1'},{name:'test2'}],map:{testOne:{name:'test1'},testTwo:{name:'test2'}}}";
MapclassMap=newHashMap();
classMap.put("list",Person.class);
classMap.put("map",Map.class);
//使用暗示,直接將json解析為指定自定義對象,其中List完全解析,Map沒有完全解析
MyBeanWithPersondiyBean=(MyBeanWithPerson)JSONObject.toBean(JSONObject.fromObject(json),MyBeanWithPerson.class,classMap);
System.out.println(diyBean);
System.out.println("dothelistrelease");
List<Person>list=diyBean.getList();
for(Persono:list){
Personp=(Person)o;
System.out.println(p.getName());
}
System.out.println("dothemaprelease");
//先往注冊器中注冊變換器,需要用到ezmorph包中的類
=JSONUtils.getMorpherRegistry();
MorpherdynaMorpher=newBeanMorpher(Person.class,morpherRegistry);
morpherRegistry.registerMorpher(dynaMorpher);
Mapmap=diyBean.getMap();
/*這里的map沒進行類型暗示,故按默認的,裡面存的為net.sf.ezmorph.bean.MorphDynaBean類型的對象*/
System.out.println(map);
/*輸出:
{testOne=net.sf.ezmorph.bean.MorphDynaBean@f73c1[
{name=test1}
],testTwo=net.sf.ezmorph.bean.MorphDynaBean@186c6b2[
{name=test2}
]}
*/
List<Person>output=newArrayList();
for(Iteratori=map.values().iterator();i.hasNext();){
//使用注冊器對指定DynaBean進行對象變換
output.add((Person)morpherRegistry.morph(Person.class,i.next()));
}
for(Personp:output){
System.out.println(p.getName());
/*輸出:
test1
test2
*/
}
}}
㈤ 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;
}
將獲取到的字元串,入庫即可。
㈥ Java的json反序列化:Java數據類可以和json數據結構不一致嗎
由於時間關系我也沒有寫全,這里提供一個思路吧。代碼如下:
Account.java:
@Data
public class Account {
private int id;
private String name;
// @PowerfulAnnotation註解是我臆想的
@PowerfulAnnotation("token.id")
private String tokenId;
@PowerfulAnnotation("token.key")
private String key;
}
㈦ java如何返回json格式
例如:
Student st1 = new Student(1, "dg", 18, new Date());
Student st2 = new Student(2, "dg", 18, new Date());
Student st3 = new Student(3, "dg", 18, new Date());
Student st4 = new Student(4, "dg", 18, new Date());
Student st5 = new Student(5, "dg", 18, new Date());
List li = new ArrayList();
JSONObject JO1 = new JSONObject(st1);
JSONObject JO2 = new JSONObject(st2);
JSONObject JO3 = new JSONObject(st3);
JSONObject JO4 = new JSONObject(st4);
JSONObject JO5 = new JSONObject(st5);
li.add(JO1);
li.add(JO2);
li.add(JO3);
li.add(JO4);
li.add(JO5);
JSONArray Ja = new JSONArray(li);
Map ma = new HashMap();
ma.put("Result", "OK");
ma.put("Records", Ja);
JSONObject js = new JSONObject(ma);
out.print(js);
返回結果:
{"Result":"OK","Records":[{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":1},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":2},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":3},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":4},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":5}]}
㈧ Java解析json數據
一、 JSON (JavaScript Object Notation)一種簡單的數據格式,比xml更輕巧。
Json建構於兩種結構:
1、「名稱/值」對的集合(A collection of name/value pairs)。不同的語言中,它被理解為對象(object),紀錄(record),結構(struct),字典(dictionary),哈希表(hash table),有鍵列表(keyed list),或者關聯數組 (associative array)。 如:
{
「name」:」jackson」,
「age」:100
}
2、值的有序列表(An ordered list of values)。在大部分語言中,它被理解為數組(array)如:
{
「students」:
[
{「name」:」jackson」,「age」:100},
{「name」:」michael」,」age」:51}
]
}
二、java解析JSON步驟
A、伺服器端將數據轉換成json字元串
首先、伺服器端項目要導入json的jar包和json所依賴的jar包至builtPath路徑下(這些可以到JSON-lib官網下載:http://json-lib.sourceforge.net/)
然後將數據轉為json字元串,核心函數是:
public static String createJsonString(String key, Object value)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
B、客戶端將json字元串轉換為相應的javaBean
1、客戶端獲取json字元串(因為android項目中已經集成了json的jar包所以這里無需導入)
public class HttpUtil
{
public static String getJsonContent(String urlStr)
{
try
{// 獲取HttpURLConnection連接對象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
// 設置連接屬性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
// 獲取相應碼
int respCode = httpConn.getResponseCode();
if (respCode == 200)
{
return ConvertStream2Json(httpConn.getInputStream());
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
private static String ConvertStream2Json(InputStream inputStream)
{
String jsonStr = "";
// ByteArrayOutputStream相當於內存輸出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 將輸入流轉移到內存輸出流中
try
{
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, len);
}
// 將內存流轉換為字元串
jsonStr = new String(out.toByteArray());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonStr;
}
}
2、獲取javaBean
public static Person getPerson(String jsonStr)
{
Person person = new Person();
try
{// 將json字元串轉換為json對象
JSONObject jsonObj = new JSONObject(jsonStr);
// 得到指定json key對象的value對象
JSONObject personObj = jsonObj.getJSONObject("person");
// 獲取之對象的所有屬性
person.setId(personObj.getInt("id"));
person.setName(personObj.getString("name"));
person.setAddress(personObj.getString("address"));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return person;
}
public static List<Person> getPersons(String jsonStr)
{
List<Person> list = new ArrayList<Person>();
JSONObject jsonObj;
try
{// 將json字元串轉換為json對象
jsonObj = new JSONObject(jsonStr);
// 得到指定json key對象的value對象
JSONArray personList = jsonObj.getJSONArray("persons");
// 遍歷jsonArray
for (int i = 0; i < personList.length(); i++)
{
// 獲取每一個json對象
JSONObject jsonItem = personList.getJSONObject(i);
// 獲取每一個json對象的值
Person person = new Person();
person.setId(jsonItem.getInt("id"));
person.setName(jsonItem.getString("name"));
person.setAddress(jsonItem.getString("address"));
list.add(person);
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}