java中JSONArray、JSONObject、List、String之间的转换「建议收藏」

2022-09-05 15:12:50 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

一、JASSONArray转为JSONObject

JSONArray result_type = new JSONArray();

StringBuffer cdsIdxType = new StringBuffer();

cdsIdxType.append(” select id from table_type “);

result_type = jdbcTemp.queryForJSONArray(cdsIdxType.toString());

JSONObject jsonObject = (JSONObject) result_type.get(i);

二、JASONArray转为List

JSONArray result_type = new JSONArray();

StringBuffer cdsIdxType = new StringBuffer();

cdsIdxType.append(” select id from table_type “);

result_type = jdbcTemp.queryForJSONArray(cdsIdxType.toString());

ArrayList list_type = new ArrayList();

for (int i = 0; i < result_type.size(); i ) {

JSONObject jsonObject = (JSONObject) result_type.get(i);

list_type.add(jsonObject.get(“id”));

}

三、JSONArray转为String

JSONArray result_type = new JSONArray();

StringBuffer cdsIdxType = new StringBuffer();

cdsIdxType.append(” select id from table_type “);

result_type = jdbcTemp.queryForJSONArray(cdsIdxType.toString());

String typeAll = “”;

ArrayList list_type = new ArrayList();

for (int i = 0; i < result_type.size(); i ) {

JSONObject jsonObject = (JSONObject) result_type.get(i);

list_type.add(jsonObject.get(“id”)); }

for(int j=0;j<list_type.size();j ){

typeAll = typeAll “‘” list_type.get(j) “‘” “,”;

}

typeAll = typeAll.substring(0, typeAll.length() -1);

四、String转换为ArrayList

String tablecode = request.getParameter(“tablecode”);

tablecode = tablecode.substring(1, tablecode.length()-1).replace(“””, “”);

String[] list = tablecode.split(“,”);

ArrayList tables = new ArrayList();

for(int i=0; i<list.length; i ){

tables.add(list[i]);

}

五.String转JSONObject

String jsonMese = “{”语文”:”88”,”数学”:”78”,”计算机”:”99”}”;

JSONObject myJson = JSONObject.fromObject(jsonMese);

六.String转JSONArray

String jsonMessage = “[{‘num’:’成绩’, ‘外语’:88, ‘历史’:65, ‘地理’:99, ‘object’:{‘aaa’:’1111′,’bbb’:’2222′,’cccc’:’3333′}},” “{‘num’:’兴趣’, ‘外语’:28, ‘历史’:45, ‘地理’:19, ‘object’:{‘aaa’:’11a11′,’bbb’:’2222′,’cccc’:’3333′}},” “{‘num’:’爱好’, ‘外语’:48, ‘历史’:62, ‘地理’:39, ‘object’:{‘aaa’:’11c11′,’bbb’:’2222′,’cccc’:’3333′}}]”;

JSONArray myJsonArray = JSONArray.fromObject(jsonMessage);

七.String转数组

String string = “a,b,c”; String [] stringArr= string.split(“,”); //注意分隔符是需要转译

如果是”abc”这种字符串,就直接

String string = “abc” ; char [] stringArr = string.toCharArray(); //注意返回值是char数组 如果要返回byte数组就直接使用getBytes方法就ok了

String string = “abc” ; byte [] stringArr = string.getBytes();

八、数组转String

char[] data={a,b,c};

String s=new String(data);

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/136697.html原文链接:https://javaforall.cn

0 人点赞