sneppets-java8

Error: Expected BEGIN_OBJECT but was STRING at line 1 column 1

Are you getting error “Expected BEGIN_OBJECT but was STRING at line 1 column 1” while parsing Json String to Json Object using Google gson library ?

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 
Expected BEGIN_OBJECT but was STRING at line 1 column 1

Expected BEGIN_OBJECT but was STRING

Let’s look at the error received and try to understand what could be the issue

Expected BEGIN_OBJECT but was STRING

You know that all JSON objects are represented using enclosed curly braces “{}“, which means that it should always begin with open curly brace “{“, if not then gson will throw expected BEGIN_OBJECT

So instead of starting with open curly brace json string started with some “String” at line 1 column 1. So check your json string that you are passing as input whether it follows JSON standard representation format.

Json Objects Syntax

Let’s consider the following example for Json Object Syntax

{name: "Paul", age: 20, city: "New York"}

Note, when you declare/ initialize json string in your Java Code, then you should use backslash in front of double quotes that used for key/value pairs as shown below.

String jsonStr = "{\"name\": \"Paul\", \"age\": 20, \"city\": \"New York\"}";

You should keep in mind the following things when you deal with Json Objects.

  • JSON objects are surrounded by curly braces {}.
  • JSON objects are written in key/value pairs.
  • Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).
  • Keys and values are separated by a colon.
  • Each key/value pair is separated by a comma.

You can also check How to convert JSON string to JsonObject using Google Gson

Further Reading

References

Subscribe
Notify of
guest

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Angelc
Angelc
1 year ago

It worked, thanks!

Munity
Munity
1 year ago

i dont know how to do it

Munity
Munity
1 year ago

nvm

Munity
Munity
1 year ago

found a another way