如何将格式异常的JSON字符串转换为Java Fencers类对象
解决格式异常JSON转Fencers对象的问题
问题根源
你提供的JSON字符串是两个独立JSON对象直接拼接的格式({...}{...}),这不符合标准JSON语法——标准多对象结构需要用数组包裹([{...}, {...}]),所以直接解析会报错。
解决步骤
1. 修正JSON字符串格式
先把异常格式的JSON转换成标准数组格式,代码里可通过字符串处理快速实现:
String json = "{\"name\":\"m\",\"nation\":\"egy\",\"id\":100}{\"name\":\"342\",\"nation\":\"egy\",\"id\":120}"; // 修正为标准JSON数组格式 String validJson = "[" + json.replace("}{", "},{") + "]";
2. 使用JSON库解析(以Jackson为例)
首先确保项目引入Jackson依赖(Maven项目在pom.xml中添加):
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> <!-- 可替换为最新稳定版 --> </dependency>
然后修改Fencers类,补充无参构造器和getter/setter方法(Jackson默认依赖这些来完成对象映射):
public class Fencers{ private String name,nation; private int id; // 添加无参构造器 public Fencers() {} public Fencers(String name, String nation,int id) { this.name = name; this.nation = nation; this.id = id; } // 添加getter/setter方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNation() { return nation; } public void setNation(String nation) { this.nation = nation; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return id+" "+name+" "+nation+"\n"; } }
最后在Main类中完成解析:
import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; class Main{ public static void main(String[] args){ String json = "{\"name\":\"m\",\"nation\":\"egy\",\"id\":100}{\"name\":\"342\",\"nation\":\"egy\",\"id\":120}"; String validJson = "[" + json.replace("}{", "},{") + "]"; try { ObjectMapper objectMapper = new ObjectMapper(); // 解析为Fencers对象列表 List<Fencers> fencersList = objectMapper.readValue(validJson, objectMapper.getTypeFactory().constructCollectionType(List.class, Fencers.class)); // 输出解析结果 for (Fencers fencer : fencersList) { System.out.println(fencer); } } catch (Exception e) { e.printStackTrace(); } } }
3. 可选:用Gson库解析
如果更习惯使用Gson,先引入依赖:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> <!-- 可替换为最新稳定版 --> </dependency>
解析代码示例:
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.List; class Main{ public static void main(String[] args){ String json = "{\"name\":\"m\",\"nation\":\"egy\",\"id\":100}{\"name\":\"342\",\"nation\":\"egy\",\"id\":120}"; String validJson = "[" + json.replace("}{", "},{") + "]"; try { Gson gson = new Gson(); List<Fencers> fencersList = gson.fromJson(validJson, new TypeToken<List<Fencers>>(){}.getType()); for (Fencers fencer : fencersList) { System.out.println(fencer); } } catch (Exception e) { e.printStackTrace(); } } }
注意事项
- 如果JSON内容中存在
}{这类特殊子串(比如对象属性值里包含该字符),直接用replace替换会出错,这种场景需要用正则匹配JSON对象的边界来处理,但绝大多数业务场景下直接替换即可满足需求。 - 确保实体类属性名和JSON中的键名完全一致,若不一致可通过
@JsonProperty(Jackson)或@SerializedName(Gson)注解做映射。
内容的提问来源于stack exchange,提问作者Moustafa Amr
相关产品推荐
相关产品推荐

