JSONArray数据转换成java List

本文介绍了一种使用 Java 对 JSON 数据进行解析的方法,并提供了两种不同的实现方式。一种是使用 net.sf.json 库,另一种则是利用阿里巴巴的 fastjson 库来解析 JSON 字符串并将其转化为 Java 对象。

原文地址:http://hi.baidu.com/chunying031/item/054f60ab431abcab28ce9de5

package no.integrasco.ingentia.news.qaedition;

public class Person {

    private String name;

    private int age;

    public String getName() {

        return name;
    }

    public void setName(String name) {

        this.name = name;
    }

    public int getAge() {

        return age;
    }

    public void setAge(int age) {

        this.age = age;
    }
}

 

package no.integrasco.ingentia.news.qaedition;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

public class JsonTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        // 转换方法1
        JSONArray array = JSONArray.fromObject("[{'name':'hehe','age':22}]");
        List<Person> list = JSONArray.toList(array, Person.class);// 过时方法
        System.out.println(list.get(0).getName());

        // 转换方法2
        List<?> list2 = JSONArray.toList(array, new Person(), new JsonConfig());//参数1为要转换的JSONArray数据,参数2为要转换的目标数据,即List盛装的数据
        Person person = (Person) list2.get(0);
        System.out.println(person.getAge());
    }

}

 

从页面接收json格式的数据,在java类里面进行解析

String jsonStr = {"name":"zfj","dd":[{"ddr":"1","encrypt":"2","ff":"1","length":"23","ffe":"editStyled","ill":"1","pkor":"2","name":"zfj","isKey":"2","alias":"ffff"}],"addRelations":[{"type":"2","ld":"zfj","ld":"2"}]}; 

将此字符串放在ruquest或者其他的变量里面,传递到后台。 

如放在reques中: 
request.getRequestDispatcher("/geServlet?data="+jsonStr).forward(request,response); 

在servlet或java类里这样接收: 
String json = request.ge[size=large][/size]tParameter("data"); 
JSONObject jsonObject = JSONObject.fromObject(data); 
String name = jsonObject.getString(“name”); 
...... 
//对于数组这样接收用 

JSONArray jan = (JSONArray) jsonObject.get("dd"); 
if(jan!=null||jan.size()!=0){ 
for(int i=0;i<ja.size();i++){ 
JSONObject jo = JSONObject.fromObject(ja.get(i)); 
String ff = jo.getString("ff"); 
                 ...... 


因为我包中没有fromObject、toList,所以用了下面的方法:


import com.alibaba.fastjson.JSON;

.

.

.

ArrayList<SystemMessageInfo> sysMessageInfoList = JSON.parseObject(resObj,

new TypeReference<ArrayList<SystemMessageInfo>>() {

});



完整的:

1.

import com.alibaba.fastjson.JSON;

public String GetMultiLangMessage(String key, String defaultString) {


try {

if (multiLangMsg.getItemObject() == null) {

sysMsgMap=new HashMap<Integer, SystemMessageInfo>();

LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();

params.put("clientName", Session.current.getComputerName());

String resObj = KSOAPServiceUtil.callWCFService(

"GetSystemMessageForList", params);

Log.e("GetMultiLangMessage resObj", resObj);

if (!PosEnvironment.isServiceReturnNull(resObj)) {

multiLangMsg.setItemObject("msg");

}


if(PosEnvironment.isServiceReturnNull(resObj)){

return defaultString;

}

else

{

ArrayList<SystemMessageInfo> sysMessageInfoList = JSON.parseObject(resObj,

new TypeReference<ArrayList<SystemMessageInfo>>() {

});

for (SystemMessageInfo systemMessageInfo : sysMessageInfoList) {

sysMsgMap.put(systemMessageInfo.getSysMegNumber(), systemMessageInfo);

}

}

}


String strValString = "";

sysMsgInfo = sysMsgMap.get(Integer.valueOf(key));

if (sysMsgInfo!=null) {

strValString = PosEnvironment.getCurrentName(sysMsgInfo.getSysMegName1(),

sysMsgInfo.getSysMegName2(),

sysMsgInfo.getSysMegName3(),

sysMsgInfo.getSysMegName4(),

sysMsgInfo.getSysMegName5());

}

if (PosEnvironment.isNullOrEmpty(strValString)) {

strValString = defaultString;

}

return strValString;

} catch (Exception e) {

if(e instanceof NetworkErrorException){

Session.current.getNavigator().getCurrentScreen().ShowMessageBox(

"", e.getMessage(), DialogButtons.OK, new Object[]{POSFEVars.SystemAlertFlag});

}

else {

Session.current.getNavigator().getCurrentScreen().ShowMessageBox(

"","Application error, please get assistance from IT administrator!", e, DialogButtons.OK);

}

return defaultString;

}


}


2.KSOAPServiceUtil.java

//calling for WCF Service by using KSoap jar.

public class KSOAPServiceUtil {


public static String serviceUrl = "";

public static String namespace = "";

public static String soap_action_path = "";


/**

* the params is call the webService's params in accordance with the order

* parameter, not necessarily in accordance with the parameter name.

* @param methodName

* @param params

* @return

*/

public static String callWCFService(String methodName,

LinkedHashMap<String, Object> params) {

String retSoapObj = null;

try {

SoapObject request = new SoapObject(namespace, methodName);

// Call method to set the parameter values, there is no argument can

// be

// omitted

// set the parsms is json

if (params != null && params.size() > 0) {

for (Map.Entry<String, Object> entry : params.entrySet()) {

if (((entry.getValue()) instanceof Integer)

|| (entry.getValue() instanceof Boolean)

|| (entry.getValue() instanceof String)) {

request.addProperty(entry.getKey().toString(),

entry.getValue());

} else {

request.addProperty(entry.getKey().toString(),

JSON.toJSONString(entry.getValue(),SerializerFeature.WriteDateUseDateFormat));

}

}

}

// Calling Webservice method generates a SOAP request message

// set the WebService version

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(

SoapEnvelope.VER11);

envelope.dotNet = true;// Here, if set to TRUE, then the server will

// get less than the parameter values

// (such

// as: these data into the database in it)

envelope.bodyOut = request;

envelope.encodingStyle = "UTF-8";


HttpTransportSE ht = new HttpTransportSE(serviceUrl);

envelope.setOutputSoapObject(request);

ht.call(soap_action_path + methodName, envelope);// using the call

// method call

// WebService

// method

retSoapObj = envelope.getResponse().toString(); // WebService method

// to obtain the

// return results

if(retSoapObj.trim().equals("anyType{}")){

retSoapObj="{}";

}

} catch (Exception e) {

}

// call the WebService namespace and method;

return retSoapObj;

}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值