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用法:

1.String转JSONObject

 

(1)json-lib(即net.sf.json.JSONObject)

String jsonMessage = "{\"语文\":\"88\",\"数学\":\"78\",\"计算机\":\"99\"}";
JSONObject  myJson = JSONObject.fromObject(jsonMessage);

(2).用阿里巴巴的fastjson的jar包

String str = "{\"baid\":null,\"32d3:\":\"null\",433:\"0x32\",032:\"ju9fw\"}";
com.alibaba.fastjson.JSONObject jm = com.alibaba.fastjson.JSON.parseObject(str);

2.String转JSONArray

String jsonMessage = "[{'num':'成绩', '外语':88, '历史':65, '地理':99, 'object':{'aaa':'1111','bbb':'2222','cccc':'3333'}}," +
兴趣', '外语':28, '历史':45, '地理':19, 'object':{'aaa':'11a11','bbb':'2222','cccc':'3333'}}," +
爱好', '外语':48, '历史':62, '地理':39, 'object':{'aaa':'11c11','bbb':'2222','cccc':'3333'}}]";
 JSONArray myJsonArray = JSONArray.fromObject(jsonMessage);
 System.out.println(myJsonArray);

3.JSON可以有两种格式,一种是对象格式的,另一种是数组对象,

{"name":"JSON","address":"北京市西城区","age":25}//JSON的对象格式的字符串
[{"name":"JSON","address":"北京市西城区","age":25}]//数据对象格式

在前端和后端进行数据传输的时候这种格式也是很受欢迎的,后端返回json格式的字符串,前台使用js中的JSON.parse()方法把JSON字符串解析为json对象,然后进行遍历,供前端使用。

Student stu=new Student();
        stu.setName("JSON");
        stu.setAge("23");
北京市西城区");
、使用JSONObject
        JSONObject json = JSONObject.fromObject(stu);

//3.2、使用JSONArray

      

JSONArray array=JSONArray.fromObject(stu);
        String strJson=json.toString();
        String strArray=array.toString();
        System.out.println("strJson:"+strJson);
        System.out.println("strArray:"+strArray);

结果:

strJson:{"address":"北京市西城区","age":"23","name":"JSON"}
strArray:[{"address":"北京市西城区","age":"23","name":"JSON"}]

4.JSON字符串java对象

//定义两种不同格式的字符串
String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}";
String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";

 //4.1使用JSONObject

JSONObject jsonObject=JSONObject.fromObject(objectStr);
        Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);

 //4.2使用JSONArray

      

JSONArray jsonArray=JSONArray.fromObject(arrayStr);
获得jsonArray的第一个元素
        Object o=jsonArray.get(0);
        JSONObject jsonObject2=JSONObject.fromObject(o);
        Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);
        System.out.println("stu:"+stu);
        System.out.println("stu2:"+stu2);
结果:   stu:Student [name=JSON, age=24, address=北京市西城区]
北京市西城区]

从上面的代码中可以看出,使用JSONObject可以轻松的把JSON格式的字符串转化为java对象,但是使用JSONArray就没那么容易了,因为它有“[]”符号,所以我们这里在获得了JSONArray的对象之后,取其第一个元素即我们需要的一个student的变形,然后使用JSONObject轻松获得。

5.list和json字符串的互转

list--转json字符串
 Student stu=new Student();
        stu.setName("JSON");
        stu.setAge("23");
北京市海淀区");
        List<Student> lists=new ArrayList<Student>();
        lists.add(stu);
      、使用JSONObject
        //JSONObject listObject=JSONObject.fromObject(lists);
     、使用JSONArray
        JSONArray listArray=JSONArray.fromObject(lists);
        //System.out.println("listObject:"+listObject.toString());
        System.out.println("listArray:"+listArray.toString());

       我把使用JSONObject的方式给注掉了,我们先看注释之前的结果,

      Exception in thread "main" net.sf.json.JSONException: 'object' is an array. Use JSONArray instead

告诉我说有一个异常,通过查看源码发现,在使用fromObject方法的时候会先进行参数类型的判断,这里就告诉我们,传入的参数是一个array类型,因为使用的ArrayList,再来看,注释之后的结果,

listArray:[{"address":"北京市海淀区","age":"23","name":"JSON"}]
json字符串--》》list
String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";
              转化为list
                List<Student> list2=(List<Student>)JSONArray.toList(JSONArray.fromObject(arrayStr), Student.class);

               

for (Student stu : list2) {
                    System.out.println(stu);
                }
                //转化为数组
                Student[] ss =(Student[])JSONArray.toArray(JSONArray.fromObject(arrayStr),Student.class);
                for (Student student : ss) {
                    System.out.println(student);
                }

结果:Student [name=JSON, age=24, address=北京市西城区]

北京市西城区]

6.map和json字符串的互转

》》json字符串
Student stu=new Student();
        stu.setName("JSON");
        stu.setAge("23");
中国上海");
        Map<String,Student> map=new HashMap<String,Student>();
        map.put("first", stu);
      、JSONObject
        JSONObject mapObject=JSONObject.fromObject(map);
        System.out.println("mapObject"+mapObject.toString());
、JSONArray
        JSONArray mapArray=JSONArray.fromObject(map);
        System.out.println("mapArray:"+mapArray.toString());

结果

mapObject{"first":{"address":"中国上海","age":"23","name":"JSON"}}
mapArray:[{"first":{"address":"中国上海","age":"23","name":"JSON"}}]

json字符串--》》map

String strObject="{\"first\":{\"address\":\"中国上海\",\"age\":\"23\",\"name\":\"JSON\"}}";
        //JSONObject
        JSONObject jsonObject=JSONObject.fromObject(strObject);
        Map map=new HashMap();
        map.put("first", Student.class);


       使用了toBean方法,需要三个参数
        MyBean my=(MyBean)JSONObject.toBean(jsonObject, MyBean.class, map);

System.out.println(my.getFirst());

结果:

Student name=JSON, age=23, address=中国上海]

7.下面是MyBean的代码,

public class MyBean {
    private Student first;
    public Student getFirst() {
        return first;
    }
    public void setFirst(Student first) {
        this.first = first;
    }

 

使用toBean()方法是传入了三个参数,第一个是JSONObject对象,第二个是MyBean.class,第三个是一个Map对象。通过MyBean可以知道此类中要有一个first的属性,且其类型为Student,要和map中的键和值类型对应,即,first对应键 first类型对应值的类型。

以上是小弟自己总结出来的有不足的地方欢迎吐槽!学如逆水行舟不进则退!!!与君共勉!