gpt4 book ai didi

java - JSONparser 读取句子中的第一个单词

转载 作者:行者123 更新时间:2023-12-02 11:01:08 32 4
gpt4 key购买 nike

我正在使用 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;

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();
}
}

但是当我执行这个程序时,我得到以下输出

{"type":"normal","text":"hello world","notifications":["user","user","user"]}

在输出中,我可以看到仅从字符串数组中选取了第一个单词;如何获取全文;

最佳答案

我不确定您是否必须使用 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);
}

输出为:

{"type":"normal","text":"hello world","notifications":["用户从 web1 收到通知","用户从 web2 收到通知","用户从 web3 收到通知"] }

关于java - JSONparser 读取句子中的第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51311029/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com