• 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"}]}}

  • 相关阅读:
    js 构造函数 constructor
    js foreach和map区别
    js 静态方法和实例方法
    学习知识点总结(es6篇)
    java1.5新特性(转)
    21 Managing the Activity Lifecycle
    Java进阶Collection集合框架概要·16
    Java进阶核心之集合框架Map下集·18
    Java进阶核心之集合框架Set·19
    Java进阶核心之集合框架List·17
  • 原文地址:https://www.cnblogs.com/pu20065226/p/9805131.html
Copyright © 2020-2023  润新知