Aarika
Aarika

Reputation: 131

Convert byte[] to custom java object

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

Upvotes: 0

Views: 1016

Answers (1)

Dakshinamurthy Karra
Dakshinamurthy Karra

Reputation: 5463

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

Upvotes: 1

Related Questions