Java系列之:生成Json字符串

一、拼接Json字符串

import com.alibaba.fastjson.JSONObject;

import java.util.concurrent.ExecutionException;

public class TestJava {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        JSONObject jsonObj = new JSONObject();

        String json_to_string = "{\"sex\":\"男\",\"name\":\"赵云\"," + "\"project" +
                "\":\"pe_powerup_prod\"}";
        System.out.println(json_to_string);
    }
}

输出如下所示:

{"sex":"男","name":"赵云","project":"pe_powerup_prod"}

二、使用JSONObject()生成字符串

import com.alibaba.fastjson.JSONObject;

import java.util.concurrent.ExecutionException;

public class TestJava {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        JSONObject jsonObj = new JSONObject();
//            Map<String, String> ingredients = new HashMap<String, String>();

        jsonObj.put("project", "nio_business_prod");

        jsonObj.put("sugar", "1kg");

        jsonObj.put("pastry", "2.4kg");

        jsonObj.put("bestEaten", "outdoors");


        System.out.println(jsonObj);


        String json_to_string = JSONObject.toJSONString(jsonObj);
        
        System.out.println(json_to_string);

    }
}

输出如下所示:

{"pastry":"2.4kg","project":"nio_business_prod","sugar":"1kg","bestEaten":"outdoors"}
{"pastry":"2.4kg","project":"nio_business_prod","sugar":"1kg","bestEaten":"outdoors"}

版权声明:本文为zhengzaifeidelushang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。