[英]Coverting a Kafka message into java object
I am trying to convert a kafka message which is received as List of string into Json object.我正在尝试将作为字符串列表接收的 kafka 消息转换为 Json object。
Following is my code snippet:以下是我的代码片段:
//Kafka consuming msg
List<String> message = KafkaMessageConsumer.consumeMessage(props.getProperty("pickbegin.topicname"));
System.out.println("Message:" +message);
I am getting the message from the kafka as:我从卡夫卡收到消息:
Message:[{
"orders": [
{
"orderId": "784",
"orderPriority": "REGULAR",
"userId": "123"
}
]
Now I am trying to covert into Java object:现在我试图转换成 Java object:
My Pojo classes are as follows:我的 Pojo 课程如下:
@Data
public class PickBeginJson {
@JsonProperty("orders")
private List<Order> mOrders;
}
And another POJO class is:另一个 POJO class 是:
@Data
public class Order {
@JsonProperty("orderId")
private String mOrderId;
@JsonProperty("orderPriority")
private String mOrderPriority;
@JsonProperty("userId")
private String mUserId;
}
My code snippet where I am trying to covert into Java object is as follows:我试图转换为 Java object 的代码片段如下:
//Json to java object
Gson gson = new Gson();
for(String i : message)
{
JsonReader reader = new JsonReader(new StringReader(i));
reader.setLenient(true);
pickBeginJson = gson.fromJson(i, PickBeginJson.class);
System.out.println("pickBeginJson"+pickBeginJson);
}
I am getting an exception:我遇到了一个例外:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 6 column 4 path $.orders[0].
I have also used ObjectMapper as:我还使用 ObjectMapper 作为:
for(String i : message)
{
pickBeginJson = objectMapper.readValue(i, PickBeginJson.class);
System.out.println("pickBeginJson"+pickBeginJson);
}
But I am getting an exception as:但我遇到了一个例外:
com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('"' (code 34)): was expecting comma to separate Object entries
at [Source: (String)"{
"orders": [
{
"orderId": "784",
"orderPriority": "REGULAR"
"userId": "123"
}
]
}
Any help will be appreciated.任何帮助将不胜感激。
I have seen your problem, it is a malformed JSON as the error message states.我已经看到您的问题,它是错误消息所述的格式错误的 JSON。 Look at your JSON in the Kafka message:
在 Kafka 消息中查看您的 JSON:
{
"orders": [
{
"orderId": "784",
"orderPriority": "REGULAR"
"userId": "123"
}
]
If you take a closer look will notice it is missing a comma between the "orderId" and "orderPriority".如果您仔细观察会发现它在“orderId”和“orderPriority”之间缺少一个逗号。 Also, it is missing a close bracket "}" in the end of the JSON.
此外,它缺少 JSON 末尾的右括号“}”。
Your JSON should be like this:你的 JSON 应该是这样的:
{
"orders":[
{
"orderId":"784",
"orderPriority":"REGULAR",
"userId":"123"
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.