You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 7下如何编写更简洁高效的通用JSON生成代码?

Java 7下通用JSON生成工具的优化方案建议

原始实现与问题

你当前使用分号分隔字符串的实现如下:

Map<String, Object> tempParam = new HashMap<>();
tempParam.put("custid", "123");
json = gson.toJson(tempParam);

String keyParams = "schema;tablename;where;clause";
String valueParams = "dbtrial;mastercustomer;" + json + ";sort=id,date_&limit=10";

String res = genJSON(keyParams, valueParams);

public static String genJSON(String keyParams, String valueParams) {
    String[] key = keyParams.split(";");
    String[] value = valueParams.split(";");

    JSONObject objectMessage = new JSONObject();
    for(int i = 0 ; i < key.length ; i++){
        objectMessage.put(key[i], value[i]);
    }

    return objectMessage.toString();
}

你尝试过数组传入的写法,但改善有限:

String[] keyParams = {"schema", "tablename", "where", "clause"};
String[] valueParams = {"dbtrial", "mastercustomer", json, "sort=id,date_&limit=10"};

public static String genJSON(String[] keyParams, String[] valueParams) {
    JSONObject objectMessage = new JSONObject();
    for(int i = 0 ; i < keyParams.length ; i++){
        objectMessage.put(keyParams[i], valueParams[i]);
    }
    return objectMessage.toString();
}

你希望实现更简洁高效、具备动态性的通用JSON生成工具,避免分号拆分的潜在问题,同时让代码更整洁。

优化方案(适配Java 7)

1. 直接传入Map参数(最稳妥的通用方案)

直接用Map承载键值对,从根源上避免键数组与值数组长度不匹配的风险,调用逻辑也更直观:

// 调用方代码
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("schema", "dbtrial");
paramMap.put("tablename", "mastercustomer");

Map<String, Object> tempParam = new HashMap<>();
tempParam.put("custid", "123");
String json = new Gson().toJson(tempParam);
paramMap.put("where", json);
paramMap.put("clause", "sort=id,date_&limit=10");

String res = genJSON(paramMap);

// 通用工具方法
public static String genJSON(Map<String, Object> paramMap) {
    JSONObject objectMessage = new JSONObject();
    for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
        objectMessage.put(entry.getKey(), entry.getValue());
    }
    return objectMessage.toString();
}

优势:动态性强,新增键值对直接put即可;无拆分字符串的性能损耗;彻底规避键值数量不匹配的bug;代码可读性高。

2. 可变参数重载(调用最简洁)

利用Java 7支持的可变参数特性,实现直接传入键值对的调用方式,同时加入参数合法性校验:

// 调用方代码
Map<String, Object> tempParam = new HashMap<>();
tempParam.put("custid", "123");
String json = new Gson().toJson(tempParam);

String res = genJSON(
    "schema", "dbtrial",
    "tablename", "mastercustomer",
    "where", json,
    "clause", "sort=id,date_&limit=10"
);

// 通用工具方法
public static String genJSON(String... keyValuePairs) {
    if (keyValuePairs.length % 2 != 0) {
        throw new IllegalArgumentException("传入的键值对数量必须为偶数");
    }
    JSONObject objectMessage = new JSONObject();
    for (int i = 0; i < keyValuePairs.length; i += 2) {
        objectMessage.put(keyValuePairs[i], keyValuePairs[i+1]);
    }
    return objectMessage.toString();
}

优势:调用代码极简,无需提前构建集合或数组;加入校验避免非法参数;适合参数数量不多的场景。

3. Builder模式(扩展性最强)

封装链式调用的Builder类,让JSON构建逻辑更优雅,同时支持后续扩展更多功能:

// 全局通用的JSON构建器类
public class JSONBuilder {
    private final JSONObject jsonObject = new JSONObject();
    
    public JSONBuilder put(String key, Object value) {
        jsonObject.put(key, value);
        return this;
    }
    
    // 可扩展:比如添加非空判断的put方法
    public JSONBuilder putIfNotNull(String key, Object value) {
        if (value != null) {
            jsonObject.put(key, value);
        }
        return this;
    }
    
    public String build() {
        return jsonObject.toString();
    }
}

// 调用方代码
Map<String, Object> tempParam = new HashMap<>();
tempParam.put("custid", "123");
String json = new Gson().toJson(tempParam);

String res = new JSONBuilder()
    .put("schema", "dbtrial")
    .put("tablename", "mastercustomer")
    .put("where", json)
    .put("clause", "sort=id,date_&limit=10")
    .build();

优势:链式调用可读性拉满;扩展性强,可按需添加更多自定义方法;作为全局工具类非常友好。

方案选择建议

  • 若追求通用稳妥、无潜在风险,优先选择Map参数方案;
  • 若调用场景参数较少,想简化调用代码,选可变参数方案;
  • 若需要长期维护、扩展功能,Builder模式是最优解。

内容的提问来源于stack exchange,提问作者mr.Gondar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:13:22