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

如何将JSON字符串数组转为JSON对象数组?(基于Jackson ObjectMapper)

解决方法

问题出在你现在是先把每个ParameterClass对象单独序列化成JSON字符串,再把这些字符串放进列表里——这样最终序列化整个列表时,自然会得到字符串数组。要改成对象数组,核心是直接让Jackson处理对象列表,而不是先转成字符串,具体修改步骤如下:

1. 修复ParameterClass的语法与序列化问题

你的类里typRef字段缺了类型声明,另外Jackson默认需要访问字段的getter方法(或字段设为public、加@JsonProperty注解)才能序列化字段,补上这些内容:

public class ParameterClass 
{
    @NonNull private final String name;
    @JsonInclude(JsonInclude.Include.NON_NULL) private final String value;
    @JsonInclude(JsonInclude.Include.NON_NULL) private final String typRef; // 补上String类型
    @JsonInclude(JsonInclude.Include.NON_NULL) private final String unit;

    private ParameterClass (@NonNull String name, String value, String typRef, String unit)
    {
        this.name = name;
        this.value = value;
        this.typRef = typRef;
        this.unit = unit;
    }

    // 新增getter方法,让Jackson能读取字段
    public String getName() { return name; }
    public String getValue() { return value; }
    public String getTypRef() { return typRef; }
    public String getUnit() { return unit; }
}

2. 修改构建方法,返回对象而非JSON字符串

原来的buildAsJson把对象转成了字符串,现在直接返回ParameterClass实例:

// 方法名可以改成更贴合语义的buildParameter
ParameterClass buildParameter(String name, String value, String typRef, String unit) {
    return new ParameterClass(name, value, typRef, unit);
}

3. 修改列表收集逻辑,存储对象而非字符串

把List<String>改成List<ParameterClass>,直接存放ParameterClass对象:

List<ParameterClass> parameters = List.of(
    buildParameter("xx", "45", "FE", "grad"),
    buildParameter("yy", "60", "TE", "cm") // 示例其他参数
);

4. 序列化包含parameters字段的父对象

假设你有一个包含parameters字段的父类(比如RequestPayload),直接让ObjectMapper序列化这个父对象即可:

class RequestPayload {
    private List<ParameterClass> parameters;

    public RequestPayload(List<ParameterClass> parameters) {
        this.parameters = parameters;
    }

    public List<ParameterClass> getParameters() { return parameters; }
}

// 序列化整个对象,得到目标格式的JSON
RequestPayload payload = new RequestPayload(parameters);
String json = objectMapper.writeValueAsString(payload);

最终生成的JSON格式如下:

{
  "parameters": [
    {
      "name": "xx",
      "value": "45",
      "typRef": "FE",
      "unit": "grad"
    },
    {
      "name": "yy",
      "value": "60",
      "typRef": "TE",
      "unit": "cm"
    }
  ]
}

内容的提问来源于stack exchange,提问作者emoleumassi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 23:30:17