gpt4 book ai didi

java - 如何用空格返回我的字符串值

转载 作者:搜寻专家 更新时间:2023-10-31 20:01:26 27 4
gpt4 key购买 nike

如何修改我的主类,以便我可以在不丢失空格的情况下接收值?

这是我的主要类(class)的一部分:

StringBuilder sb = new StringBuilder();
Scanner s = new Scanner(new FileReader(new File("C:/User/waithaka/Documents//duka.json")));
while (s.hasNext()) {
sb.append(s.next());
}
s.close();

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();

String jstring = sb.toString();
Result results = gson.fromJson(jstring, Result.class);
List<data> dat = response.getData();
for (data data : dat) {
System.out.println("The item is " + data.getItem());
}

最后一行打印没有空格的值。例如,字符串 "Black and yellow" 的值将更改为 "Blackandyellow"

最佳答案

如果查看 Scanner.java 类,您会发现空格被视为换行符。

public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN);
}

您需要将行分隔符设置为

s.useDelimiter(System.getProperty("line.separator"));

我能够复制并解决问题,下面是代码 -

JSON

{
name:"Stack-overflow",
url:"http://www.stack-overflow .com"
}

这是类

public class GsonTest {

public static void main(String[] args) throws FileNotFoundException {
StringBuilder sb = new StringBuilder();

Scanner s = new Scanner(new FileReader(new File(
"/Users/chatar/Documents/dev/projects/stack-overflow/stack-overflow/bin/C:/User/waithaka/Documents/duka.json")));

s.useDelimiter(System.getProperty("line.separator"));
while (s.hasNext()) {
String nxt = s.next();
sb.append(nxt);
}
s.close();

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();

String jstring = sb.toString();
Result results = gson.fromJson(jstring, Result.class);

System.out.println("The item is " + results);
}
}

关于java - 如何用空格返回我的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31248270/

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