如何修改我的主类,以便我可以在不丢失空格的情况下接收值?
以下是我班级的一部分:
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"
。
答案 0 :(得分:3)
如果查看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);
}
}
答案 1 :(得分:2)
我认为您的问题来自使用Scanner,因为它可能会修剪空白区域。正如您已经使用的一些Google库(Gson),我也会使用Google的guava,它的Files类有一个toString()方法,它将整个文件读取为String: