JSON数据格式转换(StringBuffer拼接json串)大全及用法
JSON是基于{“键”:“值”} 对的存在,当然我们也可以多层嵌套,对于刚刚学习JSON十分便捷而且很好用,很容理解。话不多说直接上代码:
public String queryPostInterface(String theNewInterface) throws Exception {
JSONObject jsonObject = new JSONObject(theNewInterface);
String postId = AESUtil.Decrypt(jsonObject.getString("post_id"), cKey);//帖子ID
StringBuffer sb = new StringBuffer();
int size = 0;//定义一个变量用来接收循环多少次(共多少条数据)
if(theNewInterface!=null && !"".equals(theNewInterface)){
if (postId != null && !"".equals(postId)) {
//获取帖子信息 tieba(具体业务自己查询这里只是个例子)
TyPostInfo postInfo = tyPostBarService.selpostInfoById(Long.valueOf(postId));
//查询帖子回复信息(具体业务自己查询这里只是个例子)(<TyPostbarReply>泛型是个对象)
List<TyPostbarReply> replies = tyPostBarService.selectHuiHuid(Long.valueOf(postId));
if (replies != null) {
sb.append("{\"stateCode\": " + 1 + ","); //JSON串的开头信息
sb.append(" \"message\": \"成功\",");
sb.append("\"replayList\": [");//JSON结果集
for (TyPostbarReply reply : replies) { //循环结果集,进行拼接
//获取用户ID uuid
Long userId = iUserInfoService.getIdByUserUUID(reply.getReplyUserid().toString()); //select UO.updateUserId from USER_INFO UO where id=?
UserInfoVo usesr = tyPostBarService.selectById_yb(userId);
String photo = "";
if (usesr.getUserPhoto() != null) {
photo = usesr.getUserPhoto().substring(0, usesr.getUserPhoto().lastIndexOf("."));
} else {
photo = "";
}
sb.append("{\"userPhoto\": \"" + photo.toString() + "\",");//用户照片
sb.append("\"userName\": \"" + usesr.getRealName().toString() + "\",");//用户姓名
sb.append("\"floor\": \"" + reply.getFloorNum().toString() + "\",");//楼层数
sb.append("\"barID\": \"" + postInfo.getPostBarId().toString() + "\",");//贴吧Id
sb.append("\"postID\": \"" + postInfo.getId().toString() + "\",");//帖子id
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sb.append("\"createTime\": \"" + sdf.format(reply.getCreateTime()) + "\",");//创建时间
sb.append("\"content\": \"" + reply.getReplyContent().toString() + "\"");//评论内容
size = size + 1;//循环一次+1
if (size < replies.size()) {//这里需要注意下。如果循环总条数小于查出来的总条数每次循环完毕一次都在 “ },” 加上“,” 否则不加 “ ,”
sb.append("},");
} else {
sb.append("}");
}
}
sb.append("]}"); //最后在拼接最外层(在循环外部)
}
} else {
sb.append("{\"stateCode\":" + 0 + ",");
sb.append("\"message\":\" 传入参数为空\"}");
}
}else{
sb.append("{\"stateCode\":" + 0 + ",");
sb.append("\"message\":\" 传入参数为空\"}");
}
return AESUtil.Encrypt(sb.toString(), cKey);
}
}
最后就会拼接成JSON串,具体业务具体分析,这只是一个方发,一个思想,编程重在思想!!!
解析和JSON基本用法:https://www.cnblogs.com/ysySelf/p/10985410.html
以上是最基本的拼接方式下面看下json用法:
1:创建JSONObject,添加属性
//创建JSONObject
JSONObject json = new JSONObject();
//添加属性
json.put("username", "张三");
json.put("password", "123");
//打印
System.out.println(json);
//增加属性
json.element("sex", "男");
json.put("age", 18);
System.out.println(json);
根据key返回输出 :System.out.println(json.get("sex"));
2:判断输出对象的类型
boolean isArray = json.isArray(); //是否是数组
boolean isEmpty = json.isEmpty(); // 是否为空
boolean isNullObject = json.isNullObject(); // 是否为空对象
System.out.println("是否数组:"+isArray+", 是否空:"+isEmpty+", 是否空为空对象:"+isNullObject);
3:把JSONArray添加到JSONObject中
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, "张三");
jsonArray.add(1, "123");
//开始添加
json.element("student", jsonArray);
System.out.println(json);
详细代码如下:
//创建JSONObject
JSONObject json = new JSONObject();
//添加属性
json.put("username", "张三");
json.put("password", "123");
//打印
System.out.println(json);
//增加属性
json.element("sex", "男");
json.put("age", 18);
System.out.println(json);
//根据key返回
System.out.println(json.get("sex"));
//判断输出对象的类型
boolean isArray = json.isArray();
boolean isEmpty = json.isEmpty();
boolean isNullObject = json.isNullObject();
System.out.println("是否数组:"+isArray+", 是否空:"+isEmpty+", 是否空为空对象:"+isNullObject);
System.out.println("=====");
//把JSONArray添加到JSONObject中
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, "张三");
jsonArray.add(1, "123");
//开始添加
json.element("student", jsonArray);
System.out.println(json);
JSONArray:
public static void main(String[] args) {
//创建JSONArray
JSONArray jsonArray = new JSONArray();
//添加
jsonArray.add(0, "张三");
jsonArray.add(1, "123");
jsonArray.element("男");
System.out.println(jsonArray);
//根据下标返回输出
System.out.println(jsonArray.get(0));
//根据下标设置新值,修改
jsonArray.set(0, "李四");
System.out.println(jsonArray);
//把JSONObject放入到JSONArray中
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "张三");
jsonObject.put("password", "123");
jsonArray.add(jsonObject);
System.out.println(jsonArray);
//循环输出
for(int i = 0; i < jsonArray.size(); i++) {
System.out.println(jsonArray.get(i));
}
}
JavaBean与json字符串互转
public class Student{
private String username;
private String password;
//get set
}
定义对象,JavaBean(对象)对象转json字符串
//定义对象
Student stu = new Student("张三", "123456");
//JavaBean对象转json字符串
JSONObject jsonObject = JSONObject.fromObject(stu);
System.out.println(jsonObject);
json字符串转为javaBean 关键字 toBean();
//json字符串转为javaBean
//定义json字符串
String jsondata = "{\"username\":\"李四\", \"password\":\"123\"}";
//转为json对象
JSONObject json = JSONObject.fromObject(jsondata);
//转为JavaBean对象
Student stu2 = (Student)JSONObject.toBean(json, Student.class);
System.out.println(stu2.toString());
详细代码:
public static void main(String[] args) {
//定义对象
Student stu = new Student("张三", "123456");
//JavaBean对象转json字符串
JSONObject jsonObject = JSONObject.fromObject(stu);
System.out.println(jsonObject);
//json字符串转为javaBean
//定义json字符串
String jsondata = "{\"username\":\"李四\", \"password\":\"123\"}";
//转为json对象
JSONObject json = JSONObject.fromObject(jsondata);
//转为JavaBean对象
Student stu2 = (Student)JSONObject.toBean(json, Student.class);
System.out.println(stu2.toString());
}
List与json字符串互转:
先定义list集合,list转json字符串
//定义list集合
List list = new ArrayList();
list.add(new Student("张三", "123"));
list.add(new Student("李四", "456"));
//list转json字符串
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray);
json字符串转list
//json字符串转list
List list2 = new ArrayList();
String jsondata = "[{\"password\":\"123\",\"username\":\"张三\"},{\"password\":\"456\",\"username\":\"李四\"}]";
JSONArray jsonArray1 = JSONArray.fromObject(jsondata);
for(int i = 0; i < jsonArray1.size(); i++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(i); //获取到每一条. 0:[{\"password\":\"123\",\"username\":\"张三\"} ,1:{\"password\":\"456\",\"username\":\"李四\"}
Student stu2 = (Student)JSONObject.toBean(jsonObject2, Student.class);
list2.add(stu2);wozuile
}
System.out.println(list2);
全部代码:
public static void main(String[] args) {
//定义list集合
List list = new ArrayList();
list.add(new Student("张三", "123"));
list.add(new Student("李四", "456"));
//list转json字符串
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray);
//json字符串转list
List list2 = new ArrayList();
String jsondata = "[{\"password\":\"123\",\"username\":\"张三\"},{\"password\":\"456\",\"username\":\"李四\"}]";
JSONArray jsonArray1 = JSONArray.fromObject(jsondata);
for(int i = 0; i < jsonArray1.size(); i++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
Student stu2 = (Student)JSONObject.toBean(jsonObject2, Student.class);
list2.add(stu2);
}
System.out.println(list2);
}
Map与json字符串互转:
//定义map集合
Map map = new HashMap();
map.put("1", new Student("张三", "123"));
map.put("2", new Student("李四", "456"));
//Map转json字符串
JSONObject jsonMap = JSONObject.fromObject(map);
System.out.println(jsonMap);
定义字符串map集合,map集合字符串转为map:
//定义字符串map集合
String jsondata = "{\"1\":{\"password\":\"123\",\"username\":\"张三\"},\"2\":{\"password\":\"456\",\"username\":\"李四\"}}";
//map集合字符串转为map
Map map2 = (Map)JSONObject.fromObject(jsondata); //强转Map
Set set = map2.keySet(); // 获取到所有得 key : 1 ,2
//打印 set 结果是:[1,2]
//定义迭代器,迭代输出
Iterator ite = set.iterator();
while(ite.hasNext()) { // 这里需要注意再循环中操作数据在插入到几何中一定要用迭代器
//取出一个字符串对象
String key = (String)ite.next(); // 1 ,2
//转为json格式
JSONObject jsonObject = JSONObject.fromObject(map2.get(key)); // 通过每一个Key 动态获取到对应的VALUE转换成JSON
//转为对象
Student stu = (Student)JSONObject.toBean(jsonObject, Student.class); //
System.out.println(key+" "+stu);
}
详细代码:
public static void main(String[] args) {
//定义map集合
Map map = new HashMap();
map.put("1", new Student("张三", "123"));
map.put("2", new Student("李四", "456"));
//Map转json字符串
JSONObject jsonMap = JSONObject.fromObject(map);
System.out.println(jsonMap);
//定义字符串map集合
String jsondata = "{\"1\":{\"password\":\"123\",\"username\":\"张三\"},\"2\":{\"password\":\"456\",\"username\":\"李四\"}}";
//map集合字符串转为map
Map map2 = (Map)JSONObject.fromObject(jsondata);
Set set = map2.keySet();
//定义迭代器,迭代输出
Iterator ite = set.iterator();
while(ite.hasNext()) {
//取出一个字符串对象
String key = (String)ite.next();
//转为json格式
JSONObject jsonObject = JSONObject.fromObject(map2.get(key));
//转为对象
Student stu = (Student)JSONObject.toBean(jsonObject, Student.class);
System.out.println(key+" "+stu);
}
}
JSONArray与List互转:
定义list集合,List转型JSONArray
//定义list集合
List<Student> list = new ArrayList<Student>();
list.add(new Student("张三", "123"));
list.add(new Student("李四", "456"));
//List转型JSONArray
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray.toString());
JSONArray转型List,JSONArray是用的上面的那个jsonArray变量
//JSONArray转型List
List<Student> list2 = JSONArray.toList(jsonArray, new Student(), new JsonConfig());
Iterator<Student> ite = list2.iterator();
while(ite.hasNext()) {
Student stu = ite.next();
System.out.println(stu);
}
详细代码:
public static void main(String[] args) {
//定义list集合
List<Student> list = new ArrayList<Student>();
list.add(new Student("张三", "123"));
list.add(new Student("李四", "456"));
//List转型JSONArray
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray.toString());
//JSONArray转型List
List<Student> list2 = JSONArray.toList(jsonArray, new Student(), new JsonConfig());
Iterator<Student> ite = list2.iterator();
while(ite.hasNext()) {
Student stu = ite.next();
System.out.println(stu);
}
}
运行结果:
JSONArray与数组互转:
定义数组,数组转JSONArray
//定义数组
boolean[] boolArray = {true, false, true};
//java数组转JSONArray
JSONArray jsonArray = JSONArray.fromObject(boolArray);
System.out.println(jsonArray.toString());
JSONArray转java数组:
//JSONArray转java数组
Object obj[] = jsonArray.toArray();
for(Object o : obj) {
System.out.print(o+"\t");
}
详细代码:
public static void main(String[] args) {
//定义数组
boolean[] boolArray = {true, false, true};
//java数组转JSONArray
JSONArray jsonArray = JSONArray.fromObject(boolArray);
System.out.println(jsonArray.toString());
//JSONArray转java数组
Object obj[] = jsonArray.toArray();
for(Object o : obj) {
System.out.print(o+"\t");
}
}
运行结果:
以上是小弟自己总结出来的有不足的地方欢迎吐槽!学如逆水行舟不进则退!!!与君共勉!
posted on 2019-01-02 15:28 UnmatchedSelf 阅读(5413) 评论(0) 编辑 收藏 举报