0
 private static MyClass doWork(byte[] body){        

    String data = new String(body);   
    Gson gson = new Gson();     
    final MyClass myClass = gson.fromJson(data, MyClass .class);  
    System.out.println("outsideLead"+myClass);
    return myClass;
}

byte[] body = {"N":"string","A":"string"}

When i try to convert my Byte[] to object of MyClass type, it throws me a error, that json object is expected instead a json primitive was found. What is the correct way of doing it??

6
  • a json primitive was found? you're aware that Java doesn't have primitives of json type, right? Commented Sep 17, 2018 at 6:18
  • Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive - this is the error Commented Sep 17, 2018 at 6:20
  • 1
    Please post your MyClass class and update the question with that error. Commented Sep 17, 2018 at 6:22
  • have a look at this: stackoverflow.com/questions/43644376/… Commented Sep 17, 2018 at 6:22
  • @Stultuske its gson error saying that myclass declares some field to be an object, but it is a value - number, or string eg Commented Sep 17, 2018 at 6:35

1 Answer 1

1

I guess your byte[] body doesn't contain the '{' and '}'. Try something like the following and it should work:

byte[] body = "{\"N\":\"string\",\"A\":\"string\"}".getBytes();

The error just says that instead of finding a JSON object (that always starts with a '{') - the parser got a primitive - I guess the string "N".

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

6 Comments

Thank you it works like a charm, but since my string in the program is dynamic i should write a regular expression to append escape character in front of double quotes, how do i do it
String data1 = new String(body1); data1 = data1.replaceAll("\"", "\\\"");
I tried something like this and it throws me a error:om.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path
You dont need to use "\" in the String. It is required only when you use it literally in Java code.
While then it throws me the above error when i pass it dynamically
|

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.