简体   繁体   中英

Java - How to parse json file using Gson

I have a simple json file like this

{ 
  "user":"giovanni"
}

This is the class I wrote in 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 ? Any chance it is carrying hidden characters or some other corruption ? If so maybe create a new json file and try that.

It works right for me. Please, provide stack trace.

catch JsonSynstaxException and e.printStackTrace();

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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