當前位置:首頁 » 編程語言 » java解析json

java解析json

發布時間: 2022-10-23 16:17:00

1. 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\",\"\"]]}";}}}

2. 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值。

3. java 解析json有幾種方式

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

4. 返回的json怎麼解析java

一、 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;
}

5. 如何java解析json數組

工具/原料

  • 安裝有eclipse軟體的電腦一台

  • 方法/步驟

  • 1

    首先我們在eclipse中創建一個java工程,在java工程中創建一個HelloWorld的類,在這個java的入口程序中,我們來創建一個json字元串,並且列印出來,如下圖:

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字元串

你好:

後台拆分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},");

你自己挑著用吧!

8. 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}])
*/

9. 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

10. java解析json文件

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

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

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

熱點內容
密碼編譯找規律 發布:2025-07-10 09:18:10 瀏覽:510
電影視頻緩存後 發布:2025-07-10 09:16:48 瀏覽:891
伺服器搭建需要哪些東西 發布:2025-07-10 09:15:23 瀏覽:801
無限密碼怎麼改 發布:2025-07-10 09:14:32 瀏覽:104
coc按鍵精靈腳本 發布:2025-07-10 09:12:40 瀏覽:311
excel表格ftp函數 發布:2025-07-10 09:05:50 瀏覽:276
u2game的解壓密碼 發布:2025-07-10 09:05:14 瀏覽:597
c語言編譯器ide蘋果下載 發布:2025-07-10 09:05:13 瀏覽:293
andftp埠 發布:2025-07-10 08:57:04 瀏覽:606
戰地一有什麼不用加速器的伺服器 發布:2025-07-10 08:51:33 瀏覽:405