導航:首頁 > 編程語言 > Java解析json方法

Java解析json方法

發布時間:2022-04-28 08:05:21

『壹』 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");Iterator<JSONArray> itr = jsonArr.iterator();JSONArray temp;while(itr.hasNext()) {temp = itr.next();System.out.println("===========Each JSONArray=========");for(int i = 0; i<temp.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 (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;
}

『叄』 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官網下載:http://json-lib.sourceforge.net/)然後將數據轉為json字元串,核心函數是:(Stringkey,Objectvalue){JSONObjectjsonObject=newJSONObject();jsonObject.put(key,value);returnjsonObject.toString();}B、客戶端將json字元串轉換為相應的javaBean1、客戶端獲取json字元串(因為android項目中已經集成了json的jar包所以這里無需導入)publicclassHttpUtil{(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"";}(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、獲取(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數據進行解析

2. 值的有序列表(An ordered list of values)。在大部分語言中,它被理解為數組(Array 或 List)。

下面給你例舉兩種方法:

將 Json 串轉換成 Array:

運行結果如下:

{age=90, name=Tom}

Person [id=A001, name=Jack]

『伍』 JAVA 解析JSON 怎麼做

java解析Json很簡單的呀
有個專門的JSONObject組件,把它引進來,
裡面有很多方法可以直接操作,比如:
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "aa"); // Put 方法可以根據往裡面加入屬性
String jsonString = jsonObject.getString("name"); //getString而已根據Key值取出裡面的值
你去找找JSONObject組件的用法
至於解析的目的嘛,因為用Json格式來傳輸信息可以節省網路開銷,性能上較好,Json串是一串字元串,所以接收方在接收到這個Json字元串的時候需要將它轉成對象來操作(直接操作那長長字元串是會讓人崩潰的)

希望能幫到你……

『陸』 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();
}

『柒』 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;
}

將獲取到的字元串,入庫即可。

『捌』 java解析json

JSON轉成java集合簡單步驟:1,載入:JSONArray jarr=JSONArray.fromObject(json字元串名);
2,轉換:List<類型> list=(List<類型>)JSONArray.toColleaction(jarr,類型.class);
JSON轉成java對象步驟,1,同上
2,類型如Emp(員工類)
Emp e=(Emp)JSONObject.toBean(jarr,Emp.class);

前提需要導入common的一系列的類庫,大概有6個jar包吧。
後面的需要你自己找你需要的某個字元串了。不知道是不是你所說的意思。

『玖』 java 解析json有幾種方式

JSONObject json = new JSONObject();
這個是java中獲取json用的類。
使用它的get和put就能操作json的

『拾』 java解析json文件

根據數據顯示,childern是個數組,那麼請問id是否跟此數組的下標相同,如果相同,那麼直接用

JSONArrayjsa=newJSONArray(data);//data為你獲取的json字元串
JSONObjectjObj=jsa.get(index)//index為下標
Stringvalue=jObj.getString("value");

如果不是下標,那麼只能遍歷整個數組,匹配你指定的id的json對象,然後從此對象中獲得value,獲取的方式同上

閱讀全文

與Java解析json方法相關的資料

熱點內容
壓縮機異音影響製冷嗎 瀏覽:711
德斯蘭壓縮機 瀏覽:490
程序員太極拳視頻 瀏覽:531
網上購買加密鎖 瀏覽:825
安卓為什麼軟體要隱私 瀏覽:83
虛擬主機管理源碼 瀏覽:811
java圖形圖像 瀏覽:230
單片機輸出口電平 瀏覽:486
java配置資料庫連接 瀏覽:479
java多態的體現 瀏覽:554
java的split分隔符 瀏覽:128
跪著敲代碼的程序員 瀏覽:238
web和php有什麼區別 瀏覽:120
加密的電梯卡怎麼復制蘋果手機 瀏覽:218
warez壓縮 瀏覽:137
黑馬程序員培訓機構官網天津 瀏覽:904
mainjavasrc 瀏覽:58
如何買伺服器挖礦 瀏覽:292
php批量上傳文件夾 瀏覽:560
安卓固件怎麼更新 瀏覽:169