Null values for XML attribute unmarshaling - java

This is my xml file and it is returning null values for type and currency when unmarshalling and rest all values are getting printed. I have used unmarshalling here and all Parent and Child POOJ are specified and finally my Main method calls unmarshall function
1) Vehicle.xml
<?xml version="1.0" encoding="UTF-8"?>
<Vehicle>
<car>
<manufacturer>Maruti</manufacturer>
<cost currency="INR">675000</cost>
<name type="sedan">Ciaz</name>
<fuelType>Petrol</fuelType>
<driverType>Manual</driverType>
</car>
<car>
<manufacturer>Maruti</manufacturer>
<cost currency="INR">575000</cost>
<name type="sedan">Dezire</name>
<fuelType>Petrol</fuelType>
<driverType>Manual</driverType>
</car>
</Vehicle>
Respective file are as
2) Vehicle.java
package jaxb;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "Vehicle")
public class Vehicle {
#XmlElement
private List<Car> car;
public List<Car> getCar() {
return car;
}
#Override
public String toString() {
return "Vehicle[ Car=" + car + "]";
}
}
3) Child for POJO Car.java
package jaxb;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="Car")
public class Car {
private String manufacturer;
private String name;
private String driverType;
private String fuelType;
private String currency;
#XmlAttribute
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
#XmlAttribute
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private String type;
private int cost;
#XmlElement
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public String getDriverType() {
return driverType;
}
public void setDriverType(String driverType) {
this.driverType = driverType;
}
#XmlElement
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
#XmlElement
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
#Override
public String toString() {
return "Car [name=" + name + ", fuelType=" + fuelType + ", cost=" + cost+",driverType="+driverType +",currency="+currency+ " , type="+type +"]";
}
}
4) Fie for unmarshalling
package jaxb;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class VehicleJxb {
public void unmarhalling() {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Vehicle.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Vehicle vehicle = (Vehicle) jaxbUnmarshaller.unmarshal(new File("src\\main\\java\\Data\\Vehicle.xml"));
System.out.println(vehicle);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
5) Final Output
Vehicle[ Car=[Car [name=Ciaz, fuelType=Petrol, cost=675000,driverType=Manual,currency=null , type=null], Car [name=Dezire, fuelType=Petrol, cost=575000,driverType=Manual,currency=null , type=null]]]

With JAXB you can map attributes only on the same level. To map attributes on embedded elements you should use separate classes for these elements.
Here is how you can map attributes (publci attributes used for simplicity):
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
#XmlRootElement(name = "Car")
public class Car {
public static class Cost {
#XmlValue
public String value;
#XmlAttribute
public String currency;
#Override
public String toString() {
return "Cost[value=" + value + ", currency=" + currency + "]";
}
}
public static class Name {
#XmlValue
public String value;
#XmlAttribute
public String type;
#Override
public String toString() {
return "Name[value=" + value + ", type=" + type + "]";
}
}
private String manufacturer;
private Name name;
private String driverType;
private String fuelType;
#XmlAttribute
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private String type;
private Cost cost;
#XmlElement
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
#XmlElement
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
#XmlElement
public String getDriverType() {
return driverType;
}
public void setDriverType(String driverType) {
this.driverType = driverType;
}
#XmlElement
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
#XmlElement
public Cost getCost() {
return cost;
}
public void setCost(Cost cost) {
this.cost = cost;
}
#Override
public String toString() {
return "Car [name=" + name + ", fuelType=" + fuelType + ", cost=" + cost + ",driverType=" + driverType + "]";
}
}

One common approach would be to add an extra class to handle the attribute + value. If you don't want the extra indirection when using Car. You can add a shortcut getter to it.
public class Car {
// .....
private Money cost;
public Money getCost() {
return cost;
}
public void setCost(Money cost) {
this.cost = cost;
}
/* Optional shortcut getter */
public String getCurrency(){
if(getCost()==null){
return null;
}
return getCost().getCurrency();
}
}
public static class Money {
private String currency;
private int amount;
#XmlAttribute
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
#XmlValue
public int getAmount() {
return amount;
}
public void setAmount(int cost) {
this.amount = cost;
}
}

try this:
#XmlAttribute(name = "cost currency")
public String getCurrency() {
return currency;
}
#XmlAttribute(name = "name type")
public String getType() {
return type;
}

Related

Deserialise object into a subtype dynamically using gson

I have a base class
public class Box<T> {
private T entity;
public T getEntity() {
return entity;
}
void setEntity(T entity) {
this.entity = entity;
}
}
It has 2 implementations.
// Class Person
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// Class Machine
public class Machine {
private String macAddress;
private String type;
public Machine(String macAddress, String type) {
this.macAddress = macAddress;
this.type = type;
}
}
If I want to serialise either of classA or class B objects, I will do it like this
Type typeTokenPerson = new TypeToken< Box <Person>>() {}.getType();
String userJson = gson.toJson(boxWithPersonObject, typeTokenPerson);
But the problem here is I need to know the type at compile time. I have a use case where I don't know this at compile-time, in other words, I have a json which I want to deserialize into either Person or Animal and I want to do this at runtime based on some condition.
Is there a way to do this usig Gson ?
Example:
Lets say we have a json like this
{
"entity": {
"name": "ABC",
"age": 10
}
}
This is of type Person. I want to deserialise this into an object of type Box<Person>
Gson can do it like this.
package com.example.demo;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import java.time.Duration;
import java.time.LocalDateTime;
public class GsonDemo {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private <T> Box<T> parseResponse(String responseData) {
Gson gson = new Gson();
Type jsonType = new TypeToken<Box<T>>() {
}.getType();
Box<T> result = gson.fromJson(responseData, jsonType);
return result;
}
#Test
public void test() {
LocalDateTime start = LocalDateTime.now();
try {
String json = "{ \"entity\": { \"name\": \"ABC\", \"age\": 10 }}";
Box<Person> objectBox = parseResponse(json);
System.out.println(objectBox);
String json2 = "{\n \"entity\": { \"macAddress\": \"DEF\", \"type\": \"def\" }}";
Box<Machine> objectBox2 = parseResponse(json2);
System.out.println(objectBox2);
} catch (Exception e) {
logger.error("Error", e);
}
LocalDateTime end = LocalDateTime.now();
logger.info("Cost time {}", Duration.between(start, end).toMillis() + "ms");
}
public class Box<T> {
private T entity;
public T getEntity() {
return entity;
}
void setEntity(T entity) {
this.entity = entity;
}
#Override
public String toString() {
return "Box{" + "entity=" + entity + '}';
}
}
public class Person {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public String toString() {
return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
public class Machine {
private String macAddress;
private String type;
public Machine(String macAddress, String type) {
this.macAddress = macAddress;
this.type = type;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Machine{" + "macAddress='" + macAddress + '\'' + ", type='" + type + '\'' + '}';
}
}
}

I want to 'pase xml and serve objects in rest api

` This is my xml code.Iam very new to restservice.
<?xml version="1.0" encoding="UTF-8"?>
<departments>
<deptname name="Research">
<employee>
<eid>r-001</eid>
<ename>Dinesh R</ename>
<age>35</age>
<deptcode>d1</deptcode>
<deptname>Research</deptname>
<salary>20000</salary>
</employee>
</deptname>
<deptname name="Sales">
<employee>
<eid>s-001</eid>
<ename>Kanmani S</ename>
<age>35</age>
<deptcode>d2</deptcode>
<deptname>Sales</deptname>
<salary>30000</salary>
</employee>
</deptname>
</departments>
By using this xml i want to create Restservice.I have tried , i created java classes for that(i don't know that correct or not ).but i am stuck in controller in that area how i will mapping.
Here is a simplest way, in my opinion
1) create a Departments pojo
2) create Department pojo which will be composed (composition) into departments
3) create a regular springboot controller, ensure the controller method produces and consumes application/xml
4) include below dependency in your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
here is my example,
Departments.java
import org.springframework.stereotype.Component;
#Component
public class Departments {
private List<Department> department;
public List<Department> getDepartment() {
return department;
}
public void setDepartment(List<Department> department) {
this.department = department;
}
}
Department.java
import org.springframework.stereotype.Component;
#Component
public class Department {
private String name;
private String id;
private int employeeCount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getEmployeeCount() {
return employeeCount;
}
public void setEmployeeCount(int employeeCount) {
this.employeeCount = employeeCount;
}
#Override
public String toString() {
return "Department [name=" + name + ", id=" + id + ", employeeCount=" +
employeeCount + "]";
}
public Department() { }
public Department(String name) {
this.name = name;
}
public Department(String name, String id) {
this.name=name;
this.id=id;
}
public Department(String name, String id, int employeeCount) {
this.name=name;
this.id=id;
this.employeeCount = employeeCount;
}
}
SpringBootApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(scanBasePackages = {"test.controllers","test.main", "test.model"})
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
SpringController
#RestController
public class GreetingController {
#RequestMapping("/hello/{name}")
String hello(#PathVariable String name) {
return "Hello, " + name + "!";
}
#PostMapping(path = "/departments", produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE)
#ResponseBody
Departments newEmployee(#RequestBody List<Department> departments) {
Departments departmentsObj = new Departments();
for(Department department : departments) {
System.out.println(department);
}
departmentsObj.setDepartment(departments);
return departmentsObj;
}
}

Is it okay to add an enum to a Jackson annotated class?

I have added an enum to a Class and the class is annotated with Jackson annotations. I don't want this enum to be considered during serialization or deserialization. Do I need to add any special tags to ignore the enum, like we do #JsonIgnore for methods or variables ?
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({ "name", "license", "description" })
public class Car {
#JsonProperty("name")
private String name;
#JsonProperty("license")
private String license;
#JsonProperty("description")
private String description;
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("license")
public String getLicense() {
return license;
}
#JsonProperty("license")
public void setLicense(String license) {
this.license = license;
}
#JsonProperty("description")
public String getDescription() {
return description;
}
#JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
#JsonIgnore
public Type getType() {
if(this.description.contains("electric")) {
return Type.ELECTRIC;
}else if(this.description.contains("diesel")) {
return Type.DIESEL;
}else {
return Type.UNKNOWN;
}
}
public enum Type {
ELECTRIC, DIESEL, GASOLINE, HYDROGEN, BIOFUEL, UNKNOWN
}
}
Here is some code to use this class. It works fine.
public class EnumJsonTester {
public static void main(String [] args) throws Exception {
String json = "{\r\n" +
" \"name\": \"Tesla Model S\",\r\n" +
" \"license\": \"1234\",\r\n" +
" \"description\": \"electric powered vehicle.\"\r\n" +
"}";
Car tesla = Utils.jsonToObject(json, Car.class);
System.out.println("My Car: " + tesla.getType());
}
}

jaxb returning null vaue after unmarshal

I am trying to Unmarshall a xml and it is returning null value
XML:
<letterOutHeader>
<lettertype>
MN13
</lettertype>
<letterReqid>
9294678
</letterReqid>
<language>
en
</language>
<attentionTo></attentionTo>
<addressLine1></addressLine1>
<addressLine2></addressLine2>
<city>Case City</city>
<state>NY</state>
<zipCode>59559</zipCode>
<dateOfLetter>12/28/2016</dateOfLetter>
<respondByDate/>
<externalNum>Ac0287356894754</externalNum>
<letterOutFlexField>
<name>fieldOne </name>
<value>valueOne</value>
</letterOutFlexField>
<letterOutFlexField>
<name>fieldTwo</name>
<value>valueTwo</value>
</letterOutFlexField>
<letterOutFlexField>
<name>fieldThree</name>
<value>valueThree</value>
</letterOutFlexField>
<letterOutFlexField>
<name>fieldFour</name>
<value>valueFour</value>
</letterOutFlexField>
</letterOutHeader>
Bean:
package jaxb.Bean;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class LetterOutHeader {
String lettertype;
String letterReqid;
String language;
String attentionTo;
String addressLine1;
String addressLine2;
String city;
String state;
String zipCode;
String dateOfLetter;
String respondByDate;
String externalNum;
List<LetterOutFlexFieldBean> flexFields;
#XmlAttribute
public String getLettertype() {
return lettertype;
}
public void setLettertype(String lettertype) {
this.lettertype = lettertype;
}
#XmlAttribute
public String getLetterReqid() {
return letterReqid;
}
public void setLetterReqid(String letterReqid) {
this.letterReqid = letterReqid;
}
#XmlAttribute
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
#XmlAttribute
public String getAttentionTo() {
return attentionTo;
}
public void setAttentionTo(String attentionTo) {
this.attentionTo = attentionTo;
}
#XmlAttribute
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
#XmlAttribute
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
#XmlAttribute
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#XmlAttribute
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
#XmlAttribute
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
#XmlAttribute
public String getDateOfLetter() {
return dateOfLetter;
}
public void setDateOfLetter(String dateOfLetter) {
this.dateOfLetter = dateOfLetter;
}
#XmlAttribute
public String getRespondByDate() {
return respondByDate;
}
public void setRespondByDate(String respondByDate) {
this.respondByDate = respondByDate;
}
#XmlAttribute
public String getExternalNum() {
return externalNum;
}
public void setExternalNum(String externalNum) {
this.externalNum = externalNum;
}
#XmlElement
public List<LetterOutFlexFieldBean> getFlexFields() {
return flexFields;
}
public void setFlexFields(List<LetterOutFlexFieldBean> flexFields) {
this.flexFields = flexFields;
}
}
UnMarshaling :
package jaxb.client;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import jaxb.Bean.LetterOutBean;
import jaxb.Bean.LetterOutHeader;
public class XmlToObject {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File file = new File("C:/Users/sindhu/Desktop/Kranthi/jaxB/baseXML.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(LetterOutHeader.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
LetterOutHeader que= (LetterOutHeader) jaxbUnmarshaller.unmarshal(file);
System.out.println(que.getCity());
/* System.out.println("Answers:");
List<Answer> list=que.getAnswers();
for(Answer ans:list)
System.out.println(ans.getId()+" "+ans.getAnswername()+" "+ans.getPostedby());
*/
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
I have looked into the below posts in order to avoid duplicate question
JAXB unmarshal returning null values
JAXB unmarshalling returning Null
There are many mismatch between your provided XML and JAXB class.
Firstly, there are no attributes in your sample XML, but the JAXB contains #XmlAttribute.
Secondly, it is better to declare the #XmlAccessorType explicitly or otherwise it looks for only public fields and methods.
LetterOutHeader.java
package int1.d3;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="letterOutHeader")
#XmlAccessorType(XmlAccessType.FIELD)
public class LetterOutHeader {
String lettertype;
String letterReqid;
String language;
String attentionTo;
String addressLine1;
String addressLine2;
String city;
String state;
String zipCode;
String dateOfLetter;
String respondByDate;
String externalNum;
#XmlElement(name="letterOutFlexField")
List<LetterOutFlexFieldBean> flexField;
public String getLettertype() {
return lettertype;
}
public void setLettertype(String lettertype) {
this.lettertype = lettertype;
}
public String getLetterReqid() {
return letterReqid;
}
public void setLetterReqid(String letterReqid) {
this.letterReqid = letterReqid;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getAttentionTo() {
return attentionTo;
}
public void setAttentionTo(String attentionTo) {
this.attentionTo = attentionTo;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getDateOfLetter() {
return dateOfLetter;
}
public void setDateOfLetter(String dateOfLetter) {
this.dateOfLetter = dateOfLetter;
}
public String getRespondByDate() {
return respondByDate;
}
public void setRespondByDate(String respondByDate) {
this.respondByDate = respondByDate;
}
public String getExternalNum() {
return externalNum;
}
public void setExternalNum(String externalNum) {
this.externalNum = externalNum;
}
public List<LetterOutFlexFieldBean> getFlexFields() {
if(flexField == null) {
flexField = new ArrayList<LetterOutFlexFieldBean>();
}
return this.flexField;
}
}

Gson, parsing json innerclass list, javabean

Well so I'm trying to parse a bit of JSon. I succeeded to parse:
Member.json:
{"member":{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"peter#adress.com "}}
but what if I need to parse:
{"Members":[{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":‌​‌​"peter#adress.com"},{"id":645231,"name":"Bill","profileIconId":123,"age":56,"em‌​ai‌​l":"bill#adress.com"}]}
Ofcourse I searched the web, I think, I need to use "List<>" here private List<memberProfile> member;but how do I "get" this from my main class??
I used this to parse the first string:
memeberClass.java
public class memberClass {
private memberProfile member;
public memberProfile getMember() {
return member;
}
public class memberProfile{
int id;
String name;
int profileIconId;
int age;
String email;
//Getter
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getProfileIconId() {
return profileIconId;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}
}
memberToJava.java
public class memberToJava {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader("...Member.json"));
//convert the json string back to object
memberClass memberObj = gson.fromJson(br, memberClass.class);
System.out.println("Id: " + memberObj.getMember().getId());
System.out.println("Namw: " + memberObj.getMember().getName());
System.out.println("ProfileIconId: " + memberObj.getMember().getProfileIconId());
System.out.println("Age: " + memberObj.getMember().getAge());
System.out.println("Email: " + memberObj.getMember().getEmail());
} catch (IOException e) {
e.printStackTrace();
}
}
}
see below code
MemberClass.java
import java.util.List;
public class MemberClass {
private List<MemberProfile> member;
public List<MemberProfile> getMember() {
return member;
}
public void setMember(List<MemberProfile> member) {
this.member = member;
}
public class MemberProfile {
int id;
String name;
int profileIconId;
int age;
String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getProfileIconId() {
return profileIconId;
}
public void setProfileIconId(int profileIconId) {
this.profileIconId = profileIconId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
}
Main Class
import com.google.gson.Gson;
public class MemTest {
public static void main(String[] args) {
String json = "{'member':[{'id':585897,'name':'PhPeter','profileIconId':691,'age':99,'email':‌​‌​'peter#adress.com'},{'id':645231,'name':'Bill','profileIconId':123,'age':56,'em‌​ai‌​l':'bill#adress.com'}]}";
MemberClass memberClass = new Gson().fromJson(json, MemberClass.class);
System.out.println(new Gson().toJson(memberClass));
}
}
Output
{"member":[{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"‌​‌​\u0027peter#adress.com\u0027"},{"id":645231,"name":"Bill","profileIconId":123,"age":56}]}
Hi I made some changes to your application and it seems to work now ! You where quite close alls you need is a wrapper for the array.
public class memberWrapper {
private List<memberClass> Members;
public List<memberClass> getMembers() {
return Members;
}
public void setMembers(List<memberClass> members) {
this.Members = members;
}
}
Then I changed youir original class a little:
public class memberClass {
int id;
String name;
int profileIconId;
int age;
String email;
//Getter
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getProfileIconId() {
return profileIconId;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}
and then in the main:
BufferedReader br = new BufferedReader(new FileReader("stuff.json"));
//convert the json string back to object
memberWrapper memberObj = gson.fromJson(br, memberWrapper.class);
System.out.println("Id: " + memberObj.getMembers().get(0).getId());
It should work now the important thing when dealing with JSOn is to just make sure the key matches the name of your variables.

Categories

Resources