0.加入allibab依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
1.JSON 与 各种格式的转换
//1.String --> Json对象
JSONObject jsonObject = JSONObject.parseObject(jsonString);
//获取JSON的键值对
jsonObject.getString("name");
//2.JSON --> string
String jsonString = jsonObject.toJSONString();
//3.JSON --> List<对象>
List<Conf> confList = JSONArray.parseArray(s1, Conf.class);
//4.List<对象> -- > JSON
示例 String-》JSON
System.out.println("s:"+s);
//s:{"nodes":{"bind":"ip","port":"9876","loglevel":"warning","requirepass":"pass123"}}
//转换成json格式
JSONObject json = JSONObject.parseObject(s);
System.out.println("json"+json);
//json{"nodes":{"bind":"ip","port":"9876","loglevel":"warning","requirepass":"pass123"}}
//获取其中的键值对
JSONObject nodes = JSONArray.parseObject(json.getString("nodes"));
System.out.println("node"+nodes);
//node{"bind":"ip","port":"9876","loglevel":"warning","requirepass":"pass123"}
nodes.getString("port");
//9876
2.List <--> JSON
{
"deploy-type":"single",
"nodes":[
{
"bind":"172.29.212.142",
"port":"9876",
"loglevel":"warning",
"requirepass":"pass123"
},
{
"bind":"172.29.212.142",
"port":"9876",
"loglevel":"warning",
"requirepass":"pass123"
}
]
}
思路:分为两步拿数据:1.JSON有多个Object,Object(nodes)中包含数组 2.先拿nodes的value字符串(实际为Json格式的数据) 3.nodes的值的字符串Json数据再转为List
示例 JSON--》List:把上面的JSON数据 赋值为String sss;
/**
* 取JSON的value值
*/
void JsonToObjectToArray(){
// ------------------获取object的value值--------------------
JSONObject jsonObject = JSONObject.parseObject(sss);
String nodes = jsonObject.getString("nodes");
System.out.println(nodes);
// -------------把value值转List--------------
JsonToList(nodes);
}
/**
* 提取JSON的数组值,转为List
* @param s1 格式为数组的json数据 [{"bind":"172.29.212.142"},{ "bind":"172.29.212.142"}]
*/
void JsonToList(String s1) {
List<Conf> confList = JSONArray.parseArray(s1, Conf.class);
String ip1 = confList.get(0).getBind()+":"+confList.get(0).getPort();
System.out.println(ip1);
String ip2 = confList.get(1).getBind()+":"+confList.get(1).getPort();
System.out.println(ip2);
}
示例 List--》Json
思路:把数据存到一个List集合,返回
private List<Serviceinfo> serviceinfo;
3.map转为json(JSONObject)
//JSON转map
JSONObject jsonObject = JSONObject.parseObject(str);
Map<String,Object> map = (Map<String,Object>)jsonObject; //json对象转Map
//map转JSON
String jsonString = JSON.toJSONString(map);
实例 map-》Json
Map map = new HashMap();
map.put("id","09");
map.put("name","li");
map.put("age","10");
String jsonString = JSONObject.toJSONString(map);
System.out.println(jsonString);
输出结果展示:
{"name":"li","id":"09","age":"10"}
标签:map,Java,String,JSONObject,List,JSON,字符串,nodes From: https://www.cnblogs.com/lixue333/p/16718868.html