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

如何用Java生成含多个Tag元素的ADDTNLINFO结构JSON字符串?

嘿,先给你提个关键的小问题——你给出的示例JSON其实是不符合JSON规范的!在JSON对象里,同一个键(比如这里的Tag)不能重复定义,后面的键值对会直接覆盖前面的,所以正确的做法是把多个Tag放到一个数组里,最终的JSON结构应该是这样的:

{
  "ADDTNLINFO": {
    "Tag": [
      {"name": "a", "value": "10"},
      {"name": "a b", "value": "20"},
      {"name": "a b c", "value": "30"}
    ]
  }
}

接下来我给你几种Java里常用的实现方式,涵盖不同的JSON库,你可以根据自己的项目环境选择:

方法1:使用原生org.json库(轻量,无额外依赖)

如果你的项目已经引入了Java EE的API,或者不想加额外依赖,可以用这个库:

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonGenerator {
    public static void main(String[] args) {
        // 1. 创建每个Tag的JSON对象
        JSONObject tag1 = new JSONObject();
        tag1.put("name", "a");
        tag1.put("value", "10");

        JSONObject tag2 = new JSONObject();
        tag2.put("name", "a b");
        tag2.put("value", "20");

        JSONObject tag3 = new JSONObject();
        tag3.put("name", "a b c");
        tag3.put("value", "30");

        // 2. 把所有Tag放到JSON数组里
        JSONArray tagArray = new JSONArray();
        tagArray.put(tag1);
        tagArray.put(tag2);
        tagArray.put(tag3);

        // 3. 构建ADDTNLINFO对象,把数组赋值给"Tag"键
        JSONObject addtnlInfo = new JSONObject();
        addtnlInfo.put("Tag", tagArray);

        // 4. 构建顶层对象
        JSONObject topJson = new JSONObject();
        topJson.put("ADDTNLINFO", addtnlInfo);

        // 输出格式化后的JSON字符串
        System.out.println(topJson.toString(4));
    }
}
方法2:使用Jackson库(Spring项目首选)

如果你的项目是Spring生态,Jackson基本是标配,用实体类序列化的方式更优雅:

首先定义对应的实体类(可以用Lombok简化getter/setter,这里手动写):

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

// 顶层JSON对象
public class TopLevel {
    @JsonProperty("ADDTNLINFO")
    private AddtnlInfo addtnlInfo;

    // 构造器、getter、setter
    public TopLevel(AddtnlInfo addtnlInfo) {
        this.addtnlInfo = addtnlInfo;
    }

    public AddtnlInfo getAddtnlInfo() {
        return addtnlInfo;
    }

    public void setAddtnlInfo(AddtnlInfo addtnlInfo) {
        this.addtnlInfo = addtnlInfo;
    }
}

// ADDTNLINFO对应的类
class AddtnlInfo {
    @JsonProperty("Tag")
    private List<Tag> tags;

    public AddtnlInfo(List<Tag> tags) {
        this.tags = tags;
    }

    public List<Tag> getTags() {
        return tags;
    }

    public void setTags(List<Tag> tags) {
        this.tags = tags;
    }
}

// Tag对应的类
class Tag {
    private String name;
    private String value;

    public Tag(String name, String value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

然后生成JSON的代码:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;

public class JacksonJsonGenerator {
    public static void main(String[] args) throws Exception {
        // 创建Tag列表
        List<Tag> tagList = Arrays.asList(
                new Tag("a", "10"),
                new Tag("a b", "20"),
                new Tag("a b c", "30")
        );

        // 构建对象树
        TopLevel topLevel = new TopLevel(new AddtnlInfo(tagList));

        // 序列化生成JSON
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(topLevel);

        System.out.println(json);
    }
}
方法3:使用Gson库(Google出品,轻量灵活)

Gson也是非常流行的JSON库,用法和Jackson类似:

先定义实体类(用@SerializedName指定JSON键名):

import com.google.gson.annotations.SerializedName;
import java.util.List;

class TopLevelGson {
    @SerializedName("ADDTNLINFO")
    private AddtnlInfoGson addtnlInfo;

    public TopLevelGson(AddtnlInfoGson addtnlInfo) {
        this.addtnlInfo = addtnlInfo;
    }

    // getter、setter省略
}

class AddtnlInfoGson {
    @SerializedName("Tag")
    private List<TagGson> tags;

    public AddtnlInfoGson(List<TagGson> tags) {
        this.tags = tags;
    }

    // getter、setter省略
}

class TagGson {
    private String name;
    private String value;

    public TagGson(String name, String value) {
        this.name = name;
        this.value = value;
    }

    // getter、setter省略
}

然后生成JSON的代码:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Arrays;

public class GsonJsonGenerator {
    public static void main(String[] args) {
        List<TagGson> tagList = Arrays.asList(
                new TagGson("a", "10"),
                new TagGson("a b", "20"),
                new TagGson("a b c", "30")
        );

        TopLevelGson topLevel = new TopLevelGson(new AddtnlInfoGson(tagList));

        // 创建带格式化的Gson实例
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(topLevel);

        System.out.println(json);
    }
}

最后再提醒一句:千万不要用你示例里的重复键结构,这不仅不符合JSON规范,而且在解析的时候会出现数据丢失的问题,数组才是存储多个同类型元素的正确方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:03:28