import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class test_main {
static void parseJson() throws JSONException {
String result = "[{\"username\": \"your name\", \"user_json\": {\"username\": \"your name\", \"nickname\": \"your nickname\"}}]";
JSONArray resultArray = new JSONArray(result);
JSONObject resultObj = resultArray.optJSONObject(0);
String username = resultObj.getString("username");
System.out.println(username);
JSONObject user = resultObj.getJSONObject("user_json");
String nickname = user.getString("nickname");
System.out.println(nickname);
}
static void stringToJosn() throws JSONException {
// 创建JSONObject对象
JSONObject json = new JSONObject();
// 向json中添加数据
json.put("username", "wanglihong");
json.put("height", 12.5);
json.put("age", 24);
// 创建JSONArray数组,并将json添加到数组
JSONArray array = new JSONArray();
array.put(json);
// 转换为字符串
String jsonStr = array.toString();
System.out.println(jsonStr);
}
static void setToJosn() throws JSONException {
// 初始化ArrayList集合并添加数据
List<String> list = new ArrayList<String>();
list.add("username");
list.add("age");
list.add("sex");
// 初始化HashMap集合并添加数组
Map map = new HashMap();
map.put("bookname", "CSS3实战");
map.put("price", 69.0);
// 初始化JSONArray对象,并添加数据
JSONArray array = new JSONArray();
array.put(list);
array.put(map);
String jsonStr = array.toString();
System.out.println(jsonStr);
// 生成的JSON字符串为:[["username","age","sex"],{"price":69,"bookname":"CSS3实战"}]
}
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub
// parseJson();
// stringToJosn();
setToJosn();
}
}
json简单使用
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
上一篇:Eureka注册中心
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
使用docker简单部署ELK
使用docker简单部署ELK
elasticsearch docker IP -
OpenVPN 的简单安装使用服务器 LINUX 虚拟局域网 远程连接 远程登录
-
基于python下的json的简单使用
json概述:很多程序都要求用户输入某种信息
json python 数据 -
jqGrid简单使用、json格式和jsonReader介绍
经决定使用jqGrid技术完成项目中表格展示功能,又苦于没有详细的使用说明迟迟不能实际开发时,本系列博客绝对
jqGrid json 表格 form jquery插件 -
jackson简单使用,对象转json,json转对象,json转list
n
xml json json字符串 序列化 反序列化