简体   繁体   English

Java-如何使用Gson解析json文件

[英]Java - How to parse json file using Gson

I have a simple json file like this 我有一个像这样的简单json文件

{ 
  "user":"giovanni"
}

This is the class I wrote in java: 这是我在Java中编写的类:

package maven.project;

import java.io.*;
import com.google.gson.*;

public class Prova {
    public static void main(String[] args)throws JsonSyntaxException, 
     JsonIOException, FileNotFoundException{

        String path = "/Users/matte/Desktop/project/src/main/java/maven/project/1.json";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        Gson gson = new Gson();
        JsonObject js = gson.fromJson(bufferedReader, JsonObject.class);
        String user =  js.get("user").getAsString();
        System.out.println("user: " + user);
    }
}

but running it I find this error 但是运行它我发现这个错误

Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 3 column 26
        at com.google.gson.Gson.fromJson(Gson.java:809)
        at com.google.gson.Gson.fromJson(Gson.java:734)
        at Prova.main(Prova.java:11)
Caused by: com.google.gson.stream.MalformedJsonException: Unterminated object at line 3 column 26
        at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1310)

.. ..

How can I solve? 我该如何解决?

Did you copy and paste the json file into the IDE ? 您是否将json文件复制并粘贴到IDE中? Any chance it is carrying hidden characters or some other corruption ? 它是否可能带有隐藏的字符或其他损坏? If so maybe create a new json file and try that. 如果是这样,也许创建一个新的json文件并尝试。

It works right for me. 它适合我。 Please, provide stack trace. 请提供堆栈跟踪。

catch JsonSynstaxException and e.printStackTrace();

also JsonIOException JsonIOException

The provided test passes, so I suggest you to catch exceptions may be little debugging helps: 提供的测试通过,因此我建议您捕获异常可能对调试没有什么帮助:

@RunWith(BlockJUnit4ClassRunner.class)
public class HttpServerTest {

    @Test
    public void test() throws FileNotFoundException {

        String path = "test.json";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));

        Gson gson = new Gson();
        JsonObject js = gson.fromJson(bufferedReader, JsonObject.class);
        String user = js.get("user").getAsString();
        assertEquals("giovanni", user);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM