在我的java spring项目中,我有一些带有对象的json数组。我想从字符串中获取数据,然后保存到数据库。
所以,我有: pojo class
public class Contact {
private String id;
private String name;
private String mobile;
//getters and settrs & constructors
}
我想获取如下代码的数据:
String stringdata=["{"id":"1","mobile":"1860108","name":"Intex"}",
"{"id":"21","mobile":"777717717","name":"pari"}",
"{"id":"26","mobile":"172676236","name":"pari2"}"];
try {
Contact contact1 = new Contact();
try {
contact1 = new Gson().fromJson(contactreceive, Contact.class);
}
catch (UnsupportedEncodingException uee) {
return new ResponseEntity<Object>("failed", HttpStatus.EXPECTATION_FAILED);
}
Contact contact = new Contact(contact1.getId(),contact1.getName(),contact1.getMobile());
userDao.saveContact(contact);
return new ResponseEntity<Object>("created", HttpStatus.CREATED);
} catch (Exception e) {
logger.error("Mobile User Signup > Error: " + e.getMessage());
return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
}
}
但我收到错误:
移动用户注册&gt;错误:java.lang.IllegalStateException:预期BEGIN_OBJECT但在第1行第2列是BEGIN_ARRAY
没有删除数组,我该如何获取该联系人?
答案 0 :(得分:1)
您的JSON字符串以[]
开头和结尾,因此GSON
或Jackson
或任何其他解析器将解析数组。所以为了解决这个问题,你必须这样做
List<Contact> contact1 = new ArrayList<>();
contact1 = new Gson().fromJson(contactreceive, Contact.class);
Contact contactObject = contact1.get(0);
Contact contact = new Contact(contactObject.getId(),contactObject.getName(),
contactObject.getMobile());
答案 1 :(得分:0)
当您期待单个课程时,内容包含一个数组。您需要传递Contact类的List类型,例如通过声明虚拟字段并获取其类型来执行此操作:
private static List<Contact> contactTypeField;
...
List<Contact> contacts = new Gson().fromJson(contactreceive,
MyClass.getDeclaredField("contactTypeField").getGenericType());