gpt4 book ai didi

java - Gson 解析器接受 toString 表示而不是 Json 语法

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:02 24 4
gpt4 key购买 nike

在调试一段将字符串反序列化为对象的代码时,我意识到 JSON 解析正在使用对象的 toString 表示而不是 json 表示。

波乔:

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class Pojo {

int a;
String b;
}

解析逻辑:

Gson gsonInstance =
new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setDateFormat("yyyy-MM-dd")
.create();
String json2 = "{a=5, b=field}";
Pojo obj = gsonInstance.fromJson(json2, Pojo.class);

System.out.println(obj);

当我向 Pojo 添加包含“:”的字段时,这个问题开始出现问题。就像日期一样。

围绕这个问题有两个问题:1)Gson 是如何支持这个的?我找不到任何医生。一样的。2)如何使用这种 toString 类型的实现来处理我之前提到的日期相关问题?我尝试转义 Java 字符串,但这没有帮助。

最佳答案

这是Gson的一个特性,它实际上有文档记录,但文档有点隐藏。引用:Gson.java 。 JSON反序列化最终调用的是

public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException

在代码正文中,请参阅:

reader.setLenient(true);

现在引用JsonReader.java

 public final void setLenient(boolean lenient)

该方法的 javadoc 声明如下:

/** * Configure this parser to be liberal in what it accepts. By default, * this parser is strict and only accepts JSON as specified by RFC 4627. Setting the * parser to lenient causes it to ignore the following syntax errors: * *

    *
  • Streams that start with the non-execute * prefix, ")]}'\n". *
  • Streams that include multiple top-level values. With strict parsing, * each stream must contain exactly one top-level value. *
  • Top-level values of any type. With strict parsing, the top-level * value must be an object or an array. *
  • Numbers may be {@link Double#isNaN() NaNs} or {@link * Double#isInfinite() infinities}. *
  • End of line comments starting with {@code //} or {@code #} and * ending with a newline character. *
  • C-style comments starting with {@code /*} and ending with * {@code *}{@code /}. Such comments may not be nested. *
  • Names that are unquoted or {@code 'single quoted'}. *
  • Strings that are unquoted or {@code 'single quoted'}. *
  • Array elements separated by {@code ;} instead of {@code ,}. *
  • Unnecessary array separators. These are interpreted as if null * was the omitted value. *
  • Names and values separated by {@code =} or {@code =>} instead of * {@code :}. *
  • Name/value pairs separated by {@code ;} instead of {@code ,}. *
*/

以上就是Gson解析你的字符串并反序列化它的原因。

如果您的名称/值(不带引号)有任何“:”,则上述内容将不起作用,原因是 Gson 会(在您的情况下)将其解释为 name=[value 或 anotherName???]:value (Gson 并不那么宽松)。

使用正确有效的 JSON 并反序列化。

关于java - Gson 解析器接受 toString 表示而不是 Json 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57554373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com