我的服务是JSONArray。我想将此JSONArray转换为JavaObjects(使用POJO类)。我使用Jackson API进行JSON到JavaObject的转换。我还为该转换编写了辅助类(类名:JsonUtil)。
请在下面找到我的JSON响应,包含JSONObjects和JSONArray。
[
{
"order_number":"1000123",
"customer_name":"Johnson Controls - ISC"
"order_items":[
{
"line_number":"1",
"product_code":"YMPA0100|Base",
"product_description":"YMPA0100",
"line_id":"c435d1bf-f9d4-47e6-b867-cda612429a6f",
"product_quantity":1
},
{
"line_number":"1",
"product_code":"YMPA0100|Base",
"product_description":"YMPA0100",
"line_id":"c435d1bf-f9d4-47e6-b867-cda612429a6f",
"product_quantity":2
},
{
"line_number":"1",
"product_code":"YMPA0100|Base",
"product_description":"YMPA0100",
"line_id":"c435d1bf-f9d4-47e6-b867-cda612429a6f",
"product_quantity":2
}
],
}
]
从此,如果没有呈现order_items
数组,我能够转换。如果出现order_items
数组,则意味着它会抛出以下错误。
错误:将JSON转换为Java Objects时发生异常无法从START_OBJECT令牌中反序列化java.util.ArrayList的实例 在[来源:java.io.StringReader@3444d69d; line:1,column:352](通过引用链:com.util.OrderHeader [" order_items"])
请在下面找到我的客户代码:
public class Demo {
public static <Order> void main(String[] args) {
Client client = Client.getInstance();
client.start();
String findOrderString =
client.findOrder("","1000123",").toString();
String result = findOrderString.replaceAll("[\\[\\] ]","");
System.out.println("JsonString:::"+result);
OrderHeader so=JsonUtil.convertJsonToJava(result,
OrderHeader.class);
System.out.println("==>"+so.getCustomer_name()+",
"+so.getOrder_number());
}
OrderHeader
POJO课程:
public class OrderHeader {
String order_number;
String customer_name;
List<OrderItem> order_items;
//Setters & Getters method
}
OrderItem
POJO类:(应该是OrderHeader
POJO类中的JSONArray)
public class OrderItem {
String line_id;
String line_number;
String product_code;
String product_description;
Long product_quantity;
//Getters & Setters method
}
请找到我的帮助类将JSON转换为JavaObject
public class JsonUtil {
private static ObjectMapper mapper;
static{
mapper=new ObjectMapper();
}
public static <T> T convertJsonToJava(String jsonString, Class<T> cls)
{
T result=null;
try {
result=mapper.readValue(jsonString, cls);
} catch (JsonParseException e) {
System.out.println("Exception occured while converting JSON into
Java Objects"+e.getMessage());
return result;
}
}
答案 0 :(得分:0)
您可以如下使用ObjectMapper:
private ObjectMapper objectMapper = new ObjectMapper();
List<Event> events = readValue(jsonString, new TypeReference<List<Event>>() {});
当然,您需要将其包装在try catch块中。