當前位置:首頁 » 編程語言 » java處理json字元串

java處理json字元串

發布時間: 2023-06-03 20:27:05

❶ 怎樣從java後台獲取json字元串並轉換為json對象輸出

使用json-lib.jar這個工具x0dx0apublic String getJson(Object obj){x0dx0a JSONObject json;x0dx0a json = JSONObject.fromObject(obj);x0dx0a return json.toString();x0dx0a}x0dx0a使用jquery來處理jsonx0dx0a//轉換為json數據 datas可以用ajax從後台獲取上面getJson中的數據x0dx0avar jsonDatas = eval("(" + datas + ")");x0dx0a //循環遍歷數據x0dx0ajQuery.each(jsonDatas, function(item) {x0dx0a//循環x0dx0a});

❷ 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字元串 放到數組中

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")+"=");//得到每個對象中的屬性值
}
}

❹ JAVA中如何將一個json形式的字元串轉為json對象

org.json.jsonobject
去下一個這個jar包吧。
是專用處理json字元串的。
你的這個需求如果對象單一完成可以半自動化完成。
jsonobject
json
=
new
jsonobject(json字元串)
;
if(json.has("你要解析的json是否存在")){
//.....創建你的對象。
//.....解析值並賦值給你的對象
}
如果要實現完成自動解析就得反射了。
以上回答你滿意么?

❺ 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},");

你自己挑著用吧!

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

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

❽ 關於Java處理JSON字元串的新手問題

第一點:你既然使用了net.sf.json.JSONObject對象引入了jar包直接使用其的fromObject將對象轉為字元串鬧檔效率更高,出錯的概率也更小一些。

第二點:對象中套對象的方式也很簡單,稿如如這樣

public static void main(String[] args) {

Map map1 = new HashMap();
Map map2 = new HashMap();
Map map3 = new HashMap();

map3.put("value","Male");
map2.put("gender",map3);
map1.put("attributes",map2);

JSONObject json = JSONObject.fromObject(map1);
System.out.println(json);
}

熱點內容
php伺服器搭建網站教程 發布:2024-04-24 18:29:35 瀏覽:557
安卓怎麼開一鍵啟動 發布:2024-04-24 18:12:05 瀏覽:456
phpsmarty使用 發布:2024-04-24 17:59:32 瀏覽:461
rt809f編程器軟體下載 發布:2024-04-24 17:58:01 瀏覽:66
a級車買哪個配置劃算 發布:2024-04-24 17:37:23 瀏覽:405
安卓的微信復制不了怎麼回事 發布:2024-04-24 17:32:25 瀏覽:212
我的世界伺服器控制台喊話 發布:2024-04-24 17:29:54 瀏覽:35
python保存為excel 發布:2024-04-24 17:20:31 瀏覽:369
戰艦世界什麼伺服器號 發布:2024-04-24 17:19:51 瀏覽:156
接碼平台源碼 發布:2024-04-24 17:14:29 瀏覽:149