Java JSONparser阅读句子中的第一个单词
我使用GSON库通过从变量获取输入来生成json对象,json对象还包含数组,它是字符串类型 我尝试了以下方法:Java JSONparser阅读句子中的第一个单词,java,json,gson,Java,Json,Gson,我使用GSON库通过从变量获取输入来生成json对象,json对象还包含数组,它是字符串类型 我尝试了以下方法: import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; i
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
class Hello() {
public void process() {
List<String> notifications = new ArrayList<String>();
notifications.add("user got notification from web1");
notifications.add("user got notification from web2");
notifications.add("user got notification from web3");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "normal");
jsonObject.addProperty("text", "hello world");
JsonArray array = new JsonArray();
for(String msg : notifications) {
JsonParser jsonParser = new JsonParser();
JsonReader reader = new JsonReader(new StringReader(msg));
reader.setLenient(true);
JsonElement element = jsonParser.parse(reader);
array.add(element.getAsString());
}
jsonObject.add("notifications", array);
String result = jsonObject.toString();
System.out.println(result);
}
public static void main(String a[]) {
new Hello().process();
}
}
在输出中,我可以看到仅从字符串数组中拾取第一个单词;如何获取全文 我不确定您是否必须使用JsonParser,但这似乎有效
for (String msg : notifications) {
// JsonParser jsonParser = new JsonParser();
// JsonReader reader = new JsonReader(new StringReader(msg));
// reader.setLenient(true);
// JsonElement element = jsonParser.parse(reader);
JsonPrimitive prim = new JsonPrimitive(msg);
array.add(prim);
}
输出为:
{类型:正常,文本:hello world,通知:[用户从web1收到通知,用户从web2收到通知,用户从web3收到通知]}
for (String msg : notifications) {
// JsonParser jsonParser = new JsonParser();
// JsonReader reader = new JsonReader(new StringReader(msg));
// reader.setLenient(true);
// JsonElement element = jsonParser.parse(reader);
JsonPrimitive prim = new JsonPrimitive(msg);
array.add(prim);
}