本文目錄一覽:
java 怎麼將對象轉換成json字符串
可以使用jackson的 new ObjectMapper().readValue(String, bean.class);
或者使用 JSONObject.toBean(String,bean.class);
都可以實現json轉化為bean
而 jackson 或者 JSONObject 的jar包網上均有下載,把下載的jar導入你的項目中即可。
java中字符串怎麼轉json?
string類型如果要轉換成json的話,就需要寫成這樣的形式,如下:\x0d\x0aString jsonStr =”{‘id’:’11’,’parentId’:’root’,’refObj’:{‘existType’:’exist’,’deptType’:’emp’,’treeNodeType’:’dept’}}”;\x0d\x0a JSONObject jsonObj = new JSONObject(jsonStr);\x0d\x0a JSONObject refObj = new JSONObject(jsonObj.getString(“refObj”));\x0d\x0a String existType = refObj.getString(“existType”);\x0d\x0a System.out.println(existType);\x0d\x0ajar使用的是org.json.jar
java 怎麼轉義json字符
你要字符串轉json格式,還是json轉字符串?
JSONObject json_result = new JSONObject();
json_result.put(“userId”,””);
JSONObject initParame = new JSONObject();
initParame.put(“contextConfigLocation”, “cfl”);
json_result.put(“initParameterNamesMaps”, initParame);
System.out.println(json_result);
這個是字符串轉json,你要導入json包
java Json 串中的轉義字符
一:解析普通json
1:不帶轉化字符
格式{“type”:”ONLINE_SHIPS”,”message”:{“currentTime”:1400077615368,”direction”:0,”id”:1,”latitude”:29.5506,”longitude”:106.6466}}
JSONObject jsonObject = new JSONObject(jsonstr).getJSONObject(“message”);
System.out.println(“currentTime:”+jsonObject.get(“currentTime”));
System.out.println(“direction:”+jsonObject.get(“direction”));
System.out.println(“latitude:”+jsonObject.get(“latitude”));
System.out.println(“longitude:”+jsonObject.get(“longitude”));
jsonarray
JSONObject jo = ja.getJSONArray(“cargoList”).getJSONObject(0);
2:帶轉義字符的json格式
{“type”:”ONLINE_SHIPS”,”message”:”{\”currentTime\”:1400077615368,\”direction\”:0,\”id\”:1,\”latitude\”:29.5506,\”longitude\”:106.6466}”}
其實也很簡單,先把它轉化成字符串就可以了
JSONObject jsonObject = new JSONObject(jsonstr);
//先通過字符串的方式得到,轉義字符自然會被轉化掉
String jsonstrtemp = jsonObject.getString(“message”);
System.out.println(“message:”+jsonstrtemp);
jsonObject = new JSONObject(jsonstrtemp);
System.out.println(“currentTime:”+jsonObject.get(“currentTime”));
System.out.println(“direction:”+jsonObject.get(“direction”));
System.out.println(“latitude:”+jsonObject.get(“latitude”));
System.out.println(“longitude:”+jsonObject.get(“longitude”));
二:遍歷Json對象
JSONObject ports = ja.getJSONObject(“ports”);
IteratorString keys = ports.keys();
while(keys.hasNext()){
String key=keys.next();
String value = ports.getString(key);
}
三:使用Gjson,json與對象相互轉化
使用Gson輕鬆將java對象轉化為json格式
String json = gson.toJson(Object);//得到json形式的字符串
User user = gson.fromJson(json,User.class);//得到對象
轉化成list
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lc.function.Action;
import com.lc.models.Groups;
public class MapSearch {
private void ParseData(String _data)
{
Gson gson = new Gson();
ListGroups ps = gson.fromJson(_data, new TypeTokenListGroups(){}.getType());
System.out.println(ps.get(0).getGroup_name());
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/289563.html