Conversión entre objetos JSON y Java

Este artículo está participando en el "Proyecto Piedra Dorada"

prefacio

En el desarrollo diario actual, independientemente del front-end o back-end, los datos en formato JSON se usan con más frecuencia e incluso se puede decir que son ubicuos.

El más contactado es que los datos pasados ​​en la solicitud POST generalmente se colocan en el cuerpo de la solicitud en formato JSON, y los datos devueltos por varias API en el lado del servidor se devuelven básicamente en formato JSON en el cuerpo de la respuesta. Estilo REPOSO.

Por supuesto, JSON no solo se usa en el proceso de solicitud y respuesta, sino que también debe usarse en algunos escenarios comerciales, especialmente la conversión entre objetos JSON y Java .

Por lo tanto, para nosotros en el desarrollo de Java, la conversión entre datos en formato JSON y objetos Java es inevitable.

herramienta de conversión

Existen varias herramientas de conversión principales, como se indica a continuación. Se recomienda elegir solo una de ellas para proyectos generales. Actualmente, Jackson es la que tiene los comentarios más favorables.

  • jackson

  • FastJson

  • Gson

  • Hutool

Cadena y lista JSON preparadas

Para fines de demostración, aquí hay una cadena JSON:

String jsonStr = "{\"name\" : \"GTA5\", \"price\" : 54.5}";
复制代码

Aquí hay uno dado List<Game>:

Game game1 = Game.builder().name("NBA2K23").price(new BigDecimal("198.0")).build();
Game game2 = Game.builder().name("Sim City4").price(new BigDecimal("22.5")).build();
List<Game> gameList = new ArrayList<>();
gameList.add(game1);
gameList.add(game2);
复制代码

jackson

Necesitamos usar ObjectMapperel objeto para completar la conversión:

ObjectMapper objectMapper = new ObjectMapper();
复制代码

Convierta una cadena JSON en un objeto Java: readValue

Con readValueel método , el primer parámetro es una cadena JSON y el segundo parámetro es el tipo de la clase de destino convertida.

// 将 JSON 字符串 转成 Java 对象
Game game = objectMapper.readValue(jsonStr, Game.class);
复制代码

Convierta objetos Java en cadenas JSON: writeValueAsString

Utilice writeValueAsStringel método , que acepta un objeto Java y devuelve una cadena JSON.

// 将 Java 对象转成 JSON 字符串
String gameJson = objectMapper.writeValueAsString(game);
复制代码

Convertir lista a cadena JSON: writeValueAsString

Usa también writeValueAsStringel método .

// 将 List<Game> 转成 JSON 字符串
String gameListJson = objectMapper.writeValueAsString(gameList);
复制代码

Convierta la cadena JSON a la lista: readValue

使用 readValue 方法,第一个参数是 JSON 字符串,第二个参数是转化的目标 TypeReference(类型参照)对象,这里指定其泛型为 List<Game>

// 将 JSON 字符串 转成 List<Game>
List<Game> gameListFromJson = objectMapper.readValue(gameListJson, new TypeReference<List<Game>>() {});
复制代码

总结

从 JSON 到 Java 对象,使用 readValue 方法。

从 Java 对象到 JSON,使用 writeValueAsString 方法。

FastJson

我们需要借助 FastJson 提供的 JSONObject 对象来完成转化。

将 JSON 字符串 转成 Java 对象:parseObject

使用 parseObject 方法,将 JSON 字符串解析(转化)成 Java 对象,第一个参数是 JSON 字符串,第二个参数是目标类的类型。

// 将 JSON 字符串 转成 Java 对象
Game game = JSONObject.parseObject(jsonStr, Game.class);
复制代码

将 Java 对象转成 JSON 字符串:toJSONString

使用 toJSONString 方法,将 Java 对象直接转成 JSON 字符串,接受一个 Java 对象,返回对应的 JSON 字符串。

// 将 Java 对象转成 JSON 字符串
String gameJson = JSONObject.toJSONString(game);
复制代码

将 List 转成 JSON 字符串:toJSONString

同理,可以直接丢一个 List 对象给 toJSONString 方法,把 List 转成 JSON 字符串。

// 将 List<Game> 转成 JSON 字符串
String gameListJson = JSONObject.toJSONString(gameList);
复制代码

将 JSON 字符串 转成 List:parseArray

使用 parseArray 方法,将 JSON 字符串解析成 List。2.0 版本需要调用 toJavaList 方法,得到最后的 List

// 将 JSON 字符串 转成 List<Game>
// fastjson 1.2.x 版本:List<Game> gameListFromJson = JSONObject.parseArray(gameListJson, Game.class);
List<Game> gameListFromJson = JSONArray.parseArray(gameListJson).toJavaList(Game.class);
复制代码

总结

JSON 转成 Java Bean 使用 parseObject 方法,转成 List 使用 parseArray 方法。

任意对象转成 JSON,则使用 toJSONString 方法。

Gson

我们需要借助 Gson 对象来完成转化:

Gson gson = new Gson();
复制代码

将 JSON 字符串 转成 Java 对象:fromJson

使用 fromJson 方法,两个参数的定义也是和上面两个一样的。

// 将 JSON 字符串 转成 Java 对象
Game game = gson.fromJson(jsonStr, Game.class);
复制代码

将 Java 对象转成 JSON 字符串:toJson

使用 toJson 方法,接受一个 Java 对象,然后返回对应的 JSON 字符串。

// 将 Java 对象转成 JSON 字符串
String gameJson = gson.toJson(game);
复制代码

将 List 转成 JSON 字符串:toJson

List 也是同理,使用 toJson 方法。

// 将 List<Game> 转成 JSON 字符串
String gameListJson = gson.toJson(gameList);
复制代码

将 JSON 字符串 转成 List:fromJson

这里和 Jackson 的也是类似,第二个参数使用 TypeToken 对象指定转化的目标类型为 List<Game>

// 将 JSON 字符串 转成 List<Game>
List<Game> gameListFromJson = gson.fromJson(gameListJson, new TypeToken<List<Game>>() {}.getType());
复制代码

总结

从 JSON 到 Java 对象,使用 fromJson 方法。

从 Java 对象到 JSON,使用 toJson 方法。

Hutool

我们需要借助 Hutool 提供的 JSONUtil 对象来完成转化。

将 JSON 字符串 转成 Java 对象:toBean

使用 toBean 方法,还是同样的,接受的两个参数,一个字符串,一个目标类的类型。

// 将 JSON 字符串 转成 Java 对象
Game game = JSONUtil.toBean(jsonStr, Game.class);
复制代码

将 Java 对象转成 JSON 字符串:toJsonStr

使用 toJsonStr 方法,接受一个 Java 对象,返回一个 JSON 字符串。

// 将 Java 对象转成 JSON 字符串
String gameJson = JSONUtil.toJsonStr(game);
复制代码

将 List 转成 JSON 字符串:toJsonStr

同理,也是 toJsonStr 方法。

// 将 List<Game> 转成 JSON 字符串
String gameListJson = JSONUtil.toJsonStr(gameList);
复制代码

将 JSON 字符串 转成 List:toList

使用 toList 方法,和 toBean 方法接受的参数一样。

// 将 JSON 字符串 转成 List<Game>
List<Game> gameListFromJson = JSONUtil.toList(gameListJson, Game.class);
复制代码

总结

JSON 转成 Java Bean 使用 toBean 方法,转成 List 使用 toList 方法。

Para convertir cualquier objeto en JSON, utilice toJsonStrel método .

último de los últimos

Debido a la limitación de mi nivel, es inevitable que haya errores y deficiencias, ¡ 屏幕前的靓仔靓女们si encuentras alguno, por favor, indícalo!

Finalmente, gracias por leer esto, gracias por tomar mis esfuerzos en serio y espero que este blog te sea útil.

¡Le diste un pulgar hacia arriba a la ligera, eso agregará una estrella brillante y deslumbrante al mundo en mi corazón!

Supongo que te gusta

Origin juejin.im/post/7215207897520062501
Recomendado
Clasificación