2

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?

3 Answers 3

1

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

}
Sign up to request clarification or add additional context in comments.

1 Comment

this works on my Android app too
1

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.

Comments

0

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

catch JsonSynstaxException and e.printStackTrace();

also JsonIOException

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.