zoukankan      html  css  js  c++  java
  • Java_数据交换_fastJSON_01_用法入门

    一、用法

    1.序列化—将Object转为Json对象

        Object data=JSON.toJSON( MyObject );

     注:本文的Object可以是Map、List、javaBean等

    需求:请拼接如下json

    {
      "openid": [
          "o1Pj9jmZvwSyyyyyyBa4aULW2mA", 
          "o1Pj9jmZvxxxxxxxxxULW2mA"
                   ],
      "username": [
          "afdvvf",
          "abcd"
                    ]
     }

    代码

         Map<String,List<String>>  postDataMap= new HashMap<String,List<String>>();
         postDataMap.put("openid", openIdList);
         postDataMap.put("username", userNameList);
    
         Object data=JSON.toJSON(postDataMap);
         system.out.println(data.toString());
    View Code

    2.序列化—将Object转为Json字符串

    String data=JSON.toJSONString(MyObject);

    需求:请拼接如下字符串:

    {}

    代码:

        Object ob=new Object();
        String data=JSON.toJSONString(ob);
        System.out.println(data);
    View Code

    3.反序列化—将json字符串转为JSONObject

    JSONObject jsonObject=JSON.parseObject(str);
    Data data = JSON.parseObject(str, Data.class);

    需求:将以下Json字符串转为JSONObject

    {
      "openid": [
          "o1Pj9jmZvwSyyyyyyBa4aULW2mA", 
          "o1Pj9jmZvxxxxxxxxxULW2mA"
                   ],
      "username": [
          "afdvvf",
          "abcd"
                    ]
     }

    代码:

            String str="{ " + 
                    "  "openid": [ " + 
                    "      "o1Pj9jmZvwSyyyyyyBa4aULW2mA",  " + 
                    "      "o1Pj9jmZvxxxxxxxxxULW2mA" " + 
                    "               ], " + 
                    "  "username": [ " + 
                    "      "afdvvf", " + 
                    "      "abcd" " + 
                    "                ] " + 
                    " }";
            
            JSONObject jsonObject=JSON.parseObject(str);
            System.out.println(jsonObject.toJSONString());
    View Code

    4.通过JSONObject构造json字符串

    JSONObject jsonObject=new JSONObject();
    jsonObject.put(key, value);

    需求:请构造如下json字符串

    {
        "money": 123, 
        "s_pappid": "djwhei124"
    }

    代码:

            JSONObject jsonObject=new JSONObject();
            jsonObject.put("s_pappid", "djwhei124");
            jsonObject.put("money", 123);
            
            System.out.println(jsonObject.toJSONString());
    View Code

    二、参考资料

    1.fastjson初级使用方法

    2.fastjson 使用方法

  • 相关阅读:
    业务领域建模Domain Modeling
    用例建模Use Case Modeling
    分析一套源代码的代码规范和风格并讨论如何改进优化代码
    结合工程实践选题调研分析同类软件产品
    如何提高程序员的键盘使用效率?
    第一次博客作业
    python_同时迭代多个对象
    python_判断奇偶数
    印象笔记markdown使用笔记
    【转】A*算法解决八数码问题
  • 原文地址:https://www.cnblogs.com/shirui/p/7674522.html
Copyright © 2011-2022 走看看