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

如何使用Gson将ndJSON中的多条记录映射到DTO类

解决ndJSON多记录解析问题

ndJSON的特点是每行一个独立的JSON对象,你之前的代码只调用了一次fromJson,自然只能解析第一条记录。要解析所有记录,需要循环读取每一行对应的JSON对象并添加到列表中。

修改后的代码示例

import com.google.gson.Gson;
import com.google.gson.JsonReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class NdJsonParser {
    public static void main(String[] args) {
        Gson gson = new Gson();
        List<CustomerFeedDTO> customerList = new ArrayList<>();
        
        // 使用try-with-resources自动关闭资源,避免内存泄漏
        try (JsonReader reader = new JsonReader(new FileReader("customer.json"))) {
            reader.setLenient(true); // 允许非严格的JSON格式,适配ndJSON的换行分隔规则
            while (reader.hasNext()) {
                // 每次循环解析一条记录,添加到列表中
                CustomerFeedDTO customer = gson.fromJson(reader, CustomerFeedDTO.class);
                customerList.add(customer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // 现在customerList中包含了所有解析完成的记录
        System.out.println("共解析到" + customerList.size() + "条客户记录");
    }
}

关键说明

  • reader.setLenient(true):必须开启该配置,因为ndJSON并非标准的JSON数组格式,Gson默认会严格校验格式,开启宽松模式后才能正确识别每行独立的JSON对象。
  • 循环读取逻辑:通过reader.hasNext()判断是否还有下一条记录,每次循环调用fromJson解析单个CustomerFeedDTO对象并存入列表。
  • 资源自动管理:使用try-with-resources语法自动关闭JsonReader和FileReader,避免手动关闭时出现异常遗漏。

对CustomerFeedDTO的补充建议

如果JSON字段名和类中字段名不完全匹配,需要给字段添加@SerializedName("json字段名")注解做映射,例如:

import com.google.gson.annotations.SerializedName;

public class CustomerFeedDTO {
    @SerializedName("user_profile")
    private Map<String, ?> profile;
    private Map<String, ?> phone;
    private ArrayList<?> addresses;
    private Map<String, ?> orders;
    private ArrayList<?> customs;

    // Getters and Setters
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:40:23