[英]Parsing string to JsonObject in Java
In my Java project I am constantly getting a string input such as "{type=01010201, capacity=700, auth_method=01, auth_no=090713}"在我的 Java 项目中,我不断收到一个字符串输入,例如“{type=01010201, capacity=700, auth_method=01, auth_no=090713}”
When I am trying to parse this string like below, it seems to fail当我试图像下面这样解析这个字符串时,它似乎失败了
JsonObject tot_payload = null;
try {
tot_payload = new JsonObject(obj.getString("data"));
} catch (Exception e) {
log.error("record in json parsing error");
}
I understand that this is due to the fact that I am missing the spaces for the string.我知道这是因为我缺少字符串的空格。 My application receives a variety of different strings like this and I was wondering if there would be any efficient way of turning such string into a json object.
我的应用程序接收到各种不同的字符串,就像这样,我想知道是否有任何有效的方法可以将此类字符串转换为 json object。
Assuming that it is org.json.JSONObject
, preprocessing your input into actual JSON format should solve the problem:假设它是
org.json.JSONObject
,将您的输入预处理为实际的 JSON 格式应该可以解决问题:
import static org.assertj.core.api.Assertions.assertThat;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
class JSONObjectLT {
@Test
void parseString() throws JSONException {
final String input = "{type=01010201, capacity=700, auth_method=01, auth_no=090713}";
// only works if keys/values do not contain equal signs
final String preprocessed = input.replace('=', ':');
final JSONObject json = new JSONObject(preprocessed);
assertThat(json.getString("type")).isEqualTo("01010201");
assertThat(json.getInt("capacity")).isEqualTo(700);
}
}
Maven dependency: Maven 依赖:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-json-org</artifactId>
<version>2.13.2</version>
</dependency>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.