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

时间:2018-07-12 17:01:04

标签: 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;

    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"]}

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

1 个答案:

答案 0 :(得分:1)

我不确定您是否必须使用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收到通知”] }

相关问题