gpt4 book ai didi

java - POJO 到 JSON 的转换不适用于以 "is"开头的字符串变量

转载 作者:行者123 更新时间:2023-12-01 17:43:07 25 4
gpt4 key购买 nike

字符串变量 - 下面示例中的“isInitial”未转换为 JSON。是否可以在不修改 EmployeePOJO 类的情况下为 isInitial 变量生成 JSON 结构?

PS: converting the getter method to getIsInitial works.

请找到下面用于生成 JSON 的 POJO 类:

public class EmployeePOJO {
private String firstName;
private String lastName;
private String isInitial;
private boolean isFirstNameAvailable;
private boolean hasLastNameAvailable;
private String hasHouse;


public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String isInitial()
{
return this.isInitial;
}

public void setInitial(String pInitial)
{
this.isInitial = pInitial;
}

public String getHasHouse() {
return hasHouse;
}

public void setHasHouse(String hasHouse) {
this.hasHouse = hasHouse;
}

public boolean isFirstNameAvailable() {
return isFirstNameAvailable;
}

public void setFirstNameAvailable(boolean firstNameAvailable) {
isFirstNameAvailable = firstNameAvailable;
}

public boolean isHasLastNameAvailable() {
return hasLastNameAvailable;
}

public void setHasLastNameAvailable(boolean hasLastNameAvailable) {
this.hasLastNameAvailable = hasLastNameAvailable;
}
}

POJO转换的主要逻辑如下:

import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;

public class JacksonPojoToJson {
public static void main(String[] args) throws IOException {
// Create ObjectMapper
ObjectMapper mapper = new ObjectMapper();

EmployeePOJO employeePOJO = new EmployeePOJO();
employeePOJO.setFirstName("FIRST NAME");
employeePOJO.setFirstNameAvailable(true);
employeePOJO.setLastName("last name");
employeePOJO.setHasLastNameAvailable(true);
employeePOJO.setInitial("true");

// Convert object to JSON string
String json = mapper.writeValueAsString(employeePOJO);
System.out.println(json);
}
}

最佳答案

错误的命名约定。如果您使用 IDE,请让 IDE 为您生成 getter 和 setter。

isInitial 方法可用作 boolean 变量的 getter。不是字符串变量。

这样你就可以修复你的 POJO 类 ( https://en.wikipedia.org/wiki/Plain_old_Java_object )

或者您可以使用@JsonProperty注释( https://fasterxml.github.io/jackson-annotations/javadoc/2.8/com/fasterxml/jackson/annotation/JsonProperty.html )

关于java - POJO 到 JSON 的转换不适用于以 "is"开头的字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58557126/

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