使用com.alibaba.fastjson.JSONObject构造简单的JSON数据

前端之家收集整理的这篇文章主要介绍了使用com.alibaba.fastjson.JSONObject构造简单的JSON数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用com.alibaba.fastjson.JSONObject构造一个简单的JSON数据,构造的数据类似于:

{
    "data": { "jfhf": "fff","otherData": [ { "f445": "fff","f44": "fff","f12": "fff" } ],"userData": { "ff": "fff","f1f": "fff","f2f": "fff" },"jf43hf": "ggg","jfh4f": "ggg" },"userName": "lin","password": "lin123" }

代码如下:

package com.test;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import com.alibaba.fastjson.JSONObject;

    public static void main(String[] args)
    {
        Map<String,String> param1 = new HashMap<String,String>();
        String userName = "lin";
        String password= "lin123";
        param1.put("userName",userName);
        param1.put("password",password);
        Map<String,Object> param2 = new HashMap<String,Object>();
        param2.put("jf43hf","ggg");
        param2.put("jfhf","fff");
        param2.put("jfh4f","ggg");

        Map<String,String> param3 = new HashMap<String,String>();
        param3.put("ff","fff");
        param3.put("f1f","fff");
        param3.put("f2f","fff");
        param2.put("userData",param3);


        Map<String,String> param4 = new HashMap<String,String>();
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        List<Map<String,String>> list1 = new ArrayList<Map<String,String>>();
        list1.add(param3);
        for(Map<String,String> m : list1){
            param4.put("f12","fff");
            param4.put("f445","fff");
            param4.put("f44","fff");
            list.add(param4);
        }


        param2.put("otherData",list);

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("data",param2);

        JSONObject jsonThree = new JSONObject(); 
        jsonThree.putAll(param1);
        jsonThree.putAll(jsonObject1);

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

    }

第一层就简单的包含{“userName”:”lin”,”password”:”lin123”},第二层就为data层,即为代码中的param2集合,param2这个集合放置另一列表和另一集合,并且构造出需要的json数据,大家看代码理解吧,应该挺容易的!

原文链接:https://www.f2er.com/json/288933.html

猜你在找的Json相关文章