微信小程序模板消息 java创建json示例

微信小程序文档中使用的json数据使用java方法创建,

本来我是这么创建的

  String first = "";
            /*这里的模板消息要注意最后一个需要把逗号去掉,前面的需要加上逗号*/
            keyword1 = "\"keyword1\":{" +
                    "\"value\":\"" + keyword1 + "\"," +
                    "\"color\":\"" + "#9b9b9b" + "\"" +
                    "},";
            keyword2 = "\"keyword2\":{" +
                    "\"value\":\"" + keyword2 + "\"," +
                    "\"color\":\"" + "#9b9b9b" + "\"" +
                    "},";
            keyword3 = "\"keyword3\":{" +
                    "\"value\":\"" + keyword3 + "\"," +
                    "\"color\":\"" + "#9b9b9b" + "\"" +
                    "}";
            String params = "{" +
                    "\"touser\":\"" + openId + "\"," +
                    "\"template_id\":\"" + template_id + "\"," +
                    "\"page\":\"pages/discountCoupon/discountCoupon\"," +
                    "\"form_id\":\"" + form_id + "\"," +
                    "\"data\":{" +
                    first + keyword1 + keyword2 +keyword3+
                    "}" +
                    "}";

但是这样拼出来稍微不注意就错啦现在直接使用JSONObject创建 

        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("touser", "123");
        jsonObject.accumulate("template_id","template_id");
        jsonObject.accumulate("page","page");
        jsonObject.accumulate("form_id","formId");

        jsonObject.accumulate("data", new JSONObject()
                .accumulate("keyword1", new JSONObject().accumulate("value", "123654"))
                .accumulate("keyword2", new JSONObject().accumulate("value", "987654"))
                .accumulate("keyword3",new JSONObject().accumulate("value","456"))
        );
        System.out.println(jsonObject);

结果

你可能感兴趣的:(微信小程序,java,json,微信小程序模板消息)