JSONArray数据转换成java List
2013-03-13 09:44
363 查看
原文地址: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;
}
}
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;
}
}
相关文章推荐
- JSONArray数据转换成java List
- JSONArray数据转换成java List
- java中Array/List/Map/Object与Json互相转换详解
- fastJson在java后台转换json格式数据探究(二)--处理数组/List/Map
- java中将数组、对象、Map、List转换成JSON数据
- Java中将JSON格式的数据转换成对应的Bean、Map、List数据
- java中将数组、对象、Map、List转换成JSON数据
- Java中将JSON格式的数据转换成对应的Bean、Map、List数据
- java方式的将java对象以及list或者map转化为json数据,json转换为object或者map
- list转换为JsonArray时,使用JsonValueProcessor处理有关数据类型
- java中利用jar包将list,对象等转换为json数据格式
- java中将数组、对象、Map、List转换成JSON数据
- java中Array/List/Map/Object与Json互相转换详解
- JAVA WEB 将后台传过来的jsonArray 数据转换为list集合
- Java中将JSON格式的数据转换成对应的Bean、Map、List数据
- java中将数组、对象、Map、List转换成JSON数据
- fastJson在java后台转换json格式数据探究(二)--处理数组/List/Map
- [javase][json]fastJson在java后台转换json格式数据探究--处理数组/List/Map
- java获取list集合转换成json数据
- java中Array/List/Map/Object与Json互相转换详解