zoukankan      html  css  js  c++  java
  • java json字符串与对象转换

    下载引入包gson-2.0.jar

    1.字符转数据

    final Map map = new HashMap();
    map.put("contents",
        "[{"Id":"111","AcceptNum":222,"ArchiveNum":333,"ArchivRate":444,"CUR_DATA_DT":555},{"Id":"112","AcceptNum":222,"ArchiveNum":333,"ArchivRate":444,"CUR_DATA_DT":555}]");
    map.put("footer", "{"Id":"总合计","AcceptNum":151886,"ArchiveNum":449135}");
    map.put("fields", "Id,AcceptNum,ArchiveNum,ArchivRate,CUR_DATA_DT");

    String[] fields = {};// excel字段
    String tempContent="";
    JsonArray listArray = new JsonArray(); JsonObject object = new JsonObject();
    JsonObject obj = new JsonObject();
    obj = listArray.get(1).getAsJsonObject();
    listArray
    = new JsonParser().parse(map.get("contents").toString()).getAsJsonArray();//json数组
      if (map.containsKey("footer") && !map.get("footer").toString().trim().equals("")) {
       footerJson = new JsonParser().parse(map.get("footer").toString()).getAsJsonObject();//json对象
       map.remove("footer");
      }

    fields=map.get("fields").toString().trim().split(",", -1);//普通数组
    tempContent= obj.get("Id").toString().replace(""", "");//json存取

     2.构造json对象

    JsonObject object = new JsonObject();
            // add the key/value property
    object.addProperty("code", "0");
    object.addProperty("msg", "error");
    JsonArray listArray = new JsonArray();
    JsonObject Row = new JsonObject();

    for(int rownum=1;rownum<5;rownum++){

        for (int colnum = 1; colnum <= 2; colnum++) {      // insert the cell(columnName/columnValue) into the row      

          Row.addProperty("col"+colnum, "val"+colnum);

        }

        // insert one row into listTable "List"     

      listArray.add(Row);

    }

    JsonObject subObject = new JsonObject();

    subObject.add("List", listArray);

    subObject.addProperty("page", "1");
    subObject.addProperty("page_size", "10");
    subObject.addProperty("total_count", "25");
    subObject.addProperty("page_count", "25");

    object.add("result", subObject);

    System.out.println(object.toString());

    {"code":"0","msg":"error","result":{"page":"1","page_size":"10","total_count":"25","page_count":"25","List":[{"col1":"val1","col2":"val2"},{"col1":"val1","col2":"val2"},{"col1":"val1","col2":"val2"},{"col1":"val1","col2":"val2"},{"col1":"val1","col2":"val2"}]}}

  • 相关阅读:
    WEB安全 php+mysql5注入防御(一)
    Spring 整合 Quartz 实现动态定时任务(附demo)
    dubbo工作原理(3)
    dubbo服务降级(2)
    dubbo服务降级(1)
    程序员决对不能缺少产品思维
    GNUPG
    idea远程debug:tomcat
    基于JavaMail的Java邮件发送:复杂邮件发送
    使用javaMail发送简单邮件
  • 原文地址:https://www.cnblogs.com/pu20065226/p/9805131.html
Copyright © 2011-2022 走看看