0

I have one Json String like below :

 String empJson= {"id":"13480","name":"test","salary":29292"}

I want to convert above json string into Java object.

Emp.Java

@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Emp {
 @XmlElement(name="name")
 private String m_name;
 @XmlElement(name="id")
 private String m_id;
 @XmlElement(name="salary")
 private String m_salary;
 //setters and getters
}



 GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    JsonElement jElement = gson.fromJson(empJson, JsonElement.class);
    System.out.println(jElement);
    Emp = gson.fromJson(jElement, Emp.class);
    System.out.println(" id : " + emp.getId());

But Emp object returning null values for all the fields .

Could you please help me on this.

Jyothi Sony
  • 107
  • 2
  • 13
  • Your JSON String is not valid `{"id":"13480","name":"test","salary":29292"}` should be `"{\"id\":\"13480\",\"name\":\"test\",\"salary\":29292}"`. – Paul Nov 15 '19 at 07:10
  • Try `@SerializedName` and see example in [What is the basic purpose of @SerializedName annotation in Android using Gson](https://stackoverflow.com/questions/28957285/what-is-the-basic-purpose-of-serializedname-annotation-in-android-using-gson). – LHCHIN Nov 15 '19 at 07:12
  • Possible duplicate: https://stackoverflow.com/questions/38327636/gson-java-how-can-i-make-different-names-between-mapping-and-printing – Rostyslav Barmakov Nov 15 '19 at 07:16
  • https://stackoverflow.com/help/how-to-ask – Jayakumar Thangavel Nov 15 '19 at 07:40

2 Answers2

0

Try after fixing input Json string

 String empJson= {"id":"13480","name":"test","salary":"29292"}
www.hybriscx.com
  • 1,129
  • 4
  • 22
0

By using ObjectMapper and JaxbAnnotationModule I have resolved my isssue.

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JaxbAnnotationModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Emp emp = mapper.readValue(jsonObject.toString(), Emp.class);
System.out.println("EmpName: " + emp.getName());
Jyothi Sony
  • 107
  • 2
  • 13