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??

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Aarika
  • 131
  • 2
  • 5
  • 12
  • a json primitive was found? you're aware that Java doesn't have primitives of json type, right? – Stultuske Sep 17 '18 at 06:18
  • Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive - this is the error – Aarika Sep 17 '18 at 06:20
  • 1
    Please post your `MyClass` class and update the question with that error. – Kartik Sep 17 '18 at 06:22
  • have a look at this: https://stackoverflow.com/questions/43644376/com-google-gson-jsonprimitive-cannot-be-cast-to-com-google-gson-jsonobject – Stultuske Sep 17 '18 at 06:22
  • @Stultuske its gson error saying that myclass declares some field to be an object, but it is a value - number, or string eg – Antoniossss Sep 17 '18 at 06:35
  • @Antoniossss which is clear after seeing the entire error message, not from the first one – Stultuske Sep 17 '18 at 06:38

1 Answers1

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".

Dakshinamurthy Karra
  • 5,353
  • 1
  • 17
  • 28
  • 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 – Aarika Sep 17 '18 at 06:39
  • String data1 = new String(body1); data1 = data1.replaceAll("\"", "\\\""); – Aarika Sep 17 '18 at 06:53
  • 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 – Aarika Sep 17 '18 at 06:54
  • You dont need to use "\" in the String. It is required only when you use it literally in Java code. – Dakshinamurthy Karra Sep 17 '18 at 07:05
  • While then it throws me the above error when i pass it dynamically – Aarika Sep 17 '18 at 07:09
  • Just printout your string and see whether it is a valid JSON. May be you need to prepend and append '{' and '}' to your String. Easy way to check whether your String is a valid JSON or not is to just paste into a Browser console. – Dakshinamurthy Karra Sep 17 '18 at 07:20