我对 Jakarta 的 JSON 处理有点困难。如何获取数组元素的字符串?
import jakarta.json.*;
String str = "{ \"test\": [\"abc\", \"xyz\"], \"test2\": \"blabla\" }";
JsonReader jr = Json.createReader (new StringReader (str));
JsonObject jo = jr.readObject ();
JsonString js = jo.getJsonString("test2");
System.out.println(js.toString()); // OK - "blabla"
System.out.println(js.getString()); // OK - blabla
JsonValue jv = jo.getJsonArray ("test").get(0);
System.out.println (jv.toString()); // "abc"
// how to get abc instead of "abc"?
正如评论中提到的,我们可以将值转换为
JsonString
。import jakarta.json.*;
import java.io.StringReader;
public class JakartaJsonTest {
public static void main(String[] args) {
String str = "{ \"test\": [\"abc\", \"xyz\"], \"test2\": \"blabla\" }";
JsonReader jr = Json.createReader(new StringReader(str));
JsonObject jo = jr.readObject();
JsonString jv = jo.getJsonArray("test").getJsonString(0);
System.out.println(jv.getString()); // abc
}
}