gpt4 book ai didi

java - 在 servlet 中读取 JSON 时缺少 START_ARRAY token

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

我必须从 servlet 中收到的 JSON 字符串创建 Java 对象下面是 JSON

[{"name":"name","value":"Shital"},{"name":"email","value":"swankhade@gmail.com"},{"name":"contactno","value":"9920042776"},{"name":"Address","value":"a6 102 Elementa"}]

我尝试通过将 [ 替换为 { 并将 ] 替换为 } 来更改 JSON,但它给出了一些其他错误。我遇到异常的 jackson 代码是

// 2. initiate jackson mapper
ObjectMapper mapper = new ObjectMapper();
// 3. Convert received JSON to Article
Enrole enrole = mapper.readValue(json, Enrole.class);

Enroll 类是带有 setter 和 getter 的简单 bean 类

public class Enrole {
private String name;
private String email;
private long contactno;
private String address;

最佳答案

这是方法之一

try {
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"name\":\"name\",\"value\":\"Shital\"},{\"name\":\"email\",\"value\":\"swankhade@gmail.com\"},{\"name\":\"contactno\",\"value\":\"9920042776\"},{\"name\":\"Address\",\"value\":\"a6 102 Elementa\"}]";
KeyValue[] jsonObjArr = mapper.readValue(json, KeyValue[].class);
Enrole enrol = new Enrole();
for (int i = 0; i < jsonObjArr.length; i++) {

KeyValue keyVal = jsonObjArr[i];
if ("name".equals(keyVal.getName())) {
enrol.setName(keyVal.getValue());
}
if ("email".equals(keyVal.getName())) {
enrol.setEmail(keyVal.getValue());
}
if ("contactno".equals(keyVal.getName())) {
enrol.setContactno(Long.parseLong(keyVal.getValue()));
}
if ("address".equals(keyVal.getName())) {
enrol.setAddress(keyVal.getValue());
}
}
System.out.println(enrol.getName());
System.out.println(enrol.getContactno());
System.out.println(enrol.getAddress());
System.out.println(enrol.getEmail());
} catch (Exception e) {
System.out.println("Exception " + e);
}

具有键和值的类:

class KeyValue {
private String name;
private String value;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}
}

模型类

class Enrole {
private String name;
private String email;
private long contactno;
private String address;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public long getContactno() {
return contactno;
}

public void setContactno(long contactno) {
this.contactno = contactno;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}
}

关于java - 在 servlet 中读取 JSON 时缺少 START_ARRAY token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58387597/

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