最近在开发过程中需要将json转为对象,但是json字符串中部分key(如:{“java.net.URL”:“http;//localhost”})在Java规范中不是合法的变量名,不能直接转为对象。经过查找找到以下解决方法,特此记录下以便后续使用到
1、引入gson依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
2、
使用@SerializedName注解,添加在需要转换的变量上,注解的value值填写为json字符串不合法的key
import com.google.gson.annotations.SerializedName;
public class ResultBody implements Serializable{
private static final long serialVersionUID = 1L;
@SerializedName("java.net.URL")
private String url;
@SerializedName("rc")
private Integer code;
@SerializedName("rm")
private String message;
private RequestHeader requestHeader;
private ResponseData responseData;
private AssertionResult assertionResult;
}
3、使用gson中的fromJson方法将json转为想要的对象
Gson gson = new GsonBuilder().serializeNulls().create();
TestResult testResult = gson.fromJson(str, TestResult.class);
至此json字符串成功转换成对象