在我的 Java 專案中,我不斷收到字串輸入,例如“{type=01010201, capacity=700, auth_method=01, auth_no=090713}”
當我試影像下面這樣決議這個字串時,它似乎失敗了
JsonObject tot_payload = null;
try {
tot_payload = new JsonObject(obj.getString("data"));
} catch (Exception e) {
log.error("record in json parsing error");
}
我知道這是因為我缺少字串的空格。我的應用程式接收到各種不同的字串,我想知道是否有任何有效的方法可以將此類字串轉換為 json 物件。
uj5u.com熱心網友回復:
假設它是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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465325.html
上一篇:Jsoncpp嵌套物件陣列
