I have the following JSON text (REST API URL SOURCE). How can I parse it to get ID, name, phone,city etc:
{"ID":1,"name":"aaa","phone":["345345345","1244","743"],"city":"asdasd"}
{"ID":2,"name":"bbb","phone":["234234","235","124"]}
{"ID":3,"name":"ccc","phone":["4234","6236","123"],"city":"jhjk"}
thanks.
EDIT:
I Run this code:
String var1 = output;
JSONObject obj;
try {
obj = new JSONObject(var1);
String a = obj.getString("name");
String b = obj.getString("phone");
String c = obj.getString("city");
System.out.println("name:" + a);
System.out.println("phone:" + b);
System.out.println("city:" + c);
and I got "phone" as a string .
someone can add the code to parse the phone line?
You can use Gson to parse the JSON. Simply create a class for this and Gson will do the parsing for you.
class MyClass{
#SerializedName("ID")
String ID;
#SerializedName("name")
String name;
#SerializedName("phone")
List<String> phone;
#SerializedName("city")
String city;
public MyClass(String ID, String name, List<String> phone, String city) {
this.ID = ID;
this.name = name;
this.phone = phone;
this.city = city;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPhone() {
return phone;
}
public void setPhone(List<String> phone) {
this.phone = phone;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
then in your main class or activity:
MyClass myclass= new Gson().fromJSON(jsonString,MyClass.class);
System.out.println(myclass.getID());
Make use of org.json libarary.
Afterwards, create an instance of JSONObject and JSONArray to parse the JSON String
Related
I'm using Spring boot trying to obtain a JSON response with #RestController and #GetMapping and it does not come out with JSON on the local host. This is my code. Can anyone fix this?
#SpringBootApplication
#RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#GetMapping
public List<Employee> hello () {
return List.of(
new Employee(
1L,
"Pedro",
"rt.pedrosantos#gmail.com",
LocalDate.of(1989, Month.JUNE, 21),
32
)
);
}
}
The Following is the "Employee" Class with setters and getters I created to go with it.
package com.example.employee;
import java.time.LocalDate;
public class Employee {
private Long id;
private String name;
private String email;
private LocalDate dob;
private Integer age;
public Employee() {
}
public Employee(Long id,
String name,
String email,
LocalDate dob,
Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.dob = dob;
this.age = age;
}
public Employee(String name,
String email,
LocalDate dob,
Integer age) {
this.name = name;
this.email = email;
this.dob = dob;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", dob=" + dob +
", age=" + age +
'}';
}
}
class ends here. I'm not able to properly return the code to JSON and I'm not sure why. Can anyone explain?
Edit: It returns a Json. Check if your browser or rest client is properly configured.
Previous answer:
Refer to this: As you have annotated with #RestController there is no need to do explicit json conversion. Since you're not returning a POJO, and according to the code you've posted you don't have any getters, changing it to the following does the job:
#RequestMapping(value = "hello_world", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<StringResponse> hello() {
return List.of(new StringResponse("Hello"),new StringResponse("World"));
}
}
class StringResponse {
private String response;
public StringResponse(String s) {
this.response = s;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
or use a library like Gson: There is a clean way to return string as json in a Spring Web API?
Example:
#RequestMapping(value = "hello_world", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<String> hello() {
Gson gson = new GsonBuilder().create();
Type type = new TypeToken<List<String>>() {}.getType();
String json = "[ \"Hello\", \"World\"]";
List<String> responseList = gson.fromJson(json, type);
return responseList;
}
More info: Spring MVC - How to return simple String as JSON in Rest Controller
How to return JSON data from spring Controller using #ResponseBody
Not sure what you're trying to do, but creating a model class with corresponding setters / getters should be the way.
When I use #JsonUnwrapped on nested field:
public class Person{
private int id;
#JsonUnwrapped
private Father father
//getters/setters
#Data
#AllArgsConstructor
private static class Father {
private String name;
private String surname;
}
And at the same time I use the #JsonCreator:
#JsonCreator // DESERIALIZATION: JSON -> POJO
public Person(...
#JsonProperty("name") String name,
#JsonProperty("surname") String surname) {
(...)
this.father = new Father(name, surname);
with Father being nested class.
I get the error:
Father` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creat
But when I remove the #JsonUnwrapped the field gets deserialised ok but is not flatten during serialisation.
How to assure that Father field will be serialised and deserialised flatten at the same time?
EDIT:
I paste full code:
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
private int id;
private String firstName;
private String lastName;
private boolean active;
private Address address;
private String[] languages;
#JsonIgnore private boolean isTheKing;
#JsonUnwrapped // SERIALIZATIONL POJO -> JSON
private Father father;
#JsonCreator // DESERIALIZATION: JSON -> POJO
public Student(
#JsonProperty("id") int id,
#JsonProperty("firstName") String firstName,
#JsonProperty("lastName") String lastName,
#JsonProperty("active") boolean active,
#JsonProperty("address") Address address,
#JsonProperty("languages") String[] languages,
#JsonProperty("isTheKing") boolean isTheKing,
#JsonProperty("name") String name,
#JsonProperty("surname") String surname) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.active = active;
this.address = address;
this.languages = languages;
this.isTheKing = isTheKing;
this.father = new Father(name, surname);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getLanguages() {
return languages;
}
public void setLanguages(String[] languages) {
this.languages = languages;
}
public Father getFather() {
return father;
}
public void setFather(Father father) {
this.father = father;
}
#Data
#AllArgsConstructor
static class Father {
private String name;
private String surname;
}
}
the following main method fails:
ObjectMapper mapper = new ObjectMapper();
Person myStudent =
mapper.readValue(new File("src/main/resources/data/rest/studentIN.json"), Person.class);
System.out.println(myStudent);
with error:
Exception in thread "main"
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot
construct instance of com.example.demo.Person$Father
(no Creators, like default construct, exist): cannot deserialize from
Object value (no delegate- or property-based Creator)
I use lombok:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
It should work for simple POJO model. Father class should be public:
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Person.Father father = new Person.Father();
father.setName("Wit");
father.setSurname("Pil");
Person person = new Person();
person.setId(1909);
person.setFather(father);
String json = mapper.writeValueAsString(person);
System.out.println(json);
System.out.println(mapper.readValue(json, Person.class));
}
}
class Person {
private int id;
#JsonUnwrapped
private Father father;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Father getFather() {
return father;
}
public void setFather(Father father) {
this.father = father;
}
#Override
public String toString() {
return "Person{" +
"id=" + id +
", father=" + father +
'}';
}
static class Father {
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
#Override
public String toString() {
return "Father{" +
"name='" + name + '\'' +
", surname='" + surname + '\'' +
'}';
}
}
}
Above code prints:
{
"id" : 1909,
"name" : "Wit",
"surname" : "Pil"
}
Person{id=1909, father=Father{name='Wit', surname='Pil'}}
I've tested it for many version since 2.6.7 and it works fine.
I have to map this JSONObject into a Java object.
This is my Json:
{"WALLET":{
"ID":"1234",
"BAL":"20.000",
"NAME":"Filomena",
"EMAIL":"filo#gmail.com",
"DOCS":[
{
"ID":"001",
"S":"0",
"TYPE":"CardId",
"VD":"2019"
}
],
"IBANS":[
{
"ID":"001",
"S":"1",
"DATA":"iban",
"SWIFT":"swiftCode",
"HOLDER":"holder"
}
],
"STATUS":"string",
"BLOCKED":"1",
"SDDMANDATES":[
{
"ID":"sddMandateId",
"S":"status",
"DATA":"iban",
"SWIFT":"swiftCode"
}
],
"LWID":"string",
"CARDS":[
{
"ID":"string",
"EXTRA":{
"IS3DS":"string",
"CTRY":"string",
"AUTH":"string",
"NUM":"string",
"EXP":"string",
"TYP":"string"
}
}
],
"FirstName":"string",
"LastName":"string",
"CompanyName":"string",
"CompanyDescription":"string",
"CompanyWebsite":"string"
}
}
This is my Java class:
public class Wallet {
private String id;
private String bal;
private String name;
private String email;
private List<Doc> docs;
private List<Iban> ibans;
private String status;
private String blocked;
private List<SddMandate> sddMandates ;
private String lwid;
private List<Card> cards;
private String firstName;
private String lastname;
private String companyName;
private String companyDescription;
private String companyWebSite;
public Wallet(){
}
public Wallet(String id, String bal, String name, String email, List<Doc> docs, List<Iban> ibans, String status,
String blocked, List<SddMandate> sddMandates, String lwid, List<Card> cards, String firstName,
String lastname, String companyName, String companyDescription, String companyWebSite) {
super();
this.id = id;
this.bal = bal;
this.name = name;
this.email = email;
this.docs = docs;
this.ibans = ibans;
this.status = status;
this.blocked = blocked;
this.sddMandates = sddMandates;
this.lwid = lwid;
this.cards = cards;
this.firstName = firstName;
this.lastname = lastname;
this.companyName = companyName;
this.companyDescription = companyDescription;
this.companyWebSite = companyWebSite;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBal() {
return bal;
}
public void setBal(String bal) {
this.bal = bal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Doc> getDocs() {
return docs;
}
public void setDocs(List<Doc> docs) {
this.docs = docs;
}
public List<Iban> getIbans() {
return ibans;
}
public void setIbans(List<Iban> ibans) {
this.ibans = ibans;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getBlocked() {
return blocked;
}
public void setBlocked(String blocked) {
this.blocked = blocked;
}
public List<SddMandate> getSddMandates() {
return sddMandates;
}
public void setSddMandates(List<SddMandate> sddMandates) {
this.sddMandates = sddMandates;
}
public String getLwid() {
return lwid;
}
public void setLwid(String lwid) {
this.lwid = lwid;
}
public List<Card> getCards() {
return cards;
}
public void setCards(List<Card> cards) {
this.cards = cards;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyDescription() {
return companyDescription;
}
public void setCompanyDescription(String companyDescription) {
this.companyDescription = companyDescription;
}
public String getCompanyWebSite() {
return companyWebSite;
}
public void setCompanyWebSite(String companyWebSite) {
this.companyWebSite = companyWebSite;
}
Now i'm trying to map the object with gson library.
Wallet walletDetails=gson.fromJson(rispostaGetWalletDetails.toString(), Wallet.class);
System.out.println("Balance: "+walletDetails.getBal());
Now when i try to call method on the object i have always null and not the real value.
How i can do?
You have a wrong root level.
Probably, you need to need to get one level down
JSONObject yourObject = json.get("WALLET");
Wallet walletDetails = gson.fromJson(yourObject.toString(), Wallet.class);
To have Gson handle the correct field name mapping while deserializing, you have to register a FieldNamingStrategy like this (using Java 8):
Gson gson = new GsonBuilder()
.setFieldNamingStrategy(field -> field.getName().toUpperCase())
.create();
The strategy will convert each Java field name to match those in your JSON.
This will cover almost all your fields except for those upper-camel-cased in the JSON response, such as "LastName", "CompanyName", etc. In order to map those too, your FieldNamingStrategy will have to become a little bit smarter, like:
field -> {
String fname = field.getName();
return "firstName".equals(fname) || "companyName".equals(fname) /*etc...*/ ? capitalize(fname) : fname.toUpperCase();
}
and so on, I think you got the idea.
The capitalize() method you can find in libraries like Apache Commons Lang or write your own, it's just for examplification here.
Your object variable name doesn't match the json attribute name. "EMAIL" in json should have same EMAIL in object. To overcome this, you could mention #JsonProperty before your attribute declaraction.
for eg:
#JsonProperty("EMAIL")
private String email;
This question already has answers here:
Serialize Java List to XML using Jackson XML mapper
(3 answers)
Closed 5 years ago.
I am learning to use Jackson to serialize XML. My class structure is as below.
class City {
#JacksonXmlProperty(localName = "CityName")
String cityName;
public City(String cityName) {
this.cityName = cityName;
}
public String getcityName() {
return cityName;
}
public void setcity(String cityName) {
this.cityName = cityName;
}
}
#JacksonXmlRootElement(localName = "Person")
class Person {
#JacksonXmlProperty(localName = "name")
private String name;
#JacksonXmlProperty(localName = "age")
private String age;
#JacksonXmlProperty(localName = "city")
private List<City> city;
public Person() { }
Person(String name, String age, List<City> city) {
this.name = name;
this.age = age;
this.city = city;
}
public String getname() {
return name;
}
public String getage() {
return age;
}
public List<City> getcity() {
return city;
}
public void setname(String name) {
this.name = name;
}
public void setage(String age) {
this.age = age;
}
public void setcity(List<City> city) {
this.city = city;
}
}
When I try to serialize a class to XML using Jackson, I get two tags for <city>
public class App
{
public static void main( String[] args )
{
try {
XmlMapper xmlMapper2 = new XmlMapper();
Person p = new Person();
City c1 = new City("abc");
City c2 = new City("def");
City c3 = new City("ghi");
List<City> cityList = new ArrayList<City>();
cityList.add(c1);
cityList.add(c2);
cityList.add(c3);
p.setname("setattr");
p.setage("55");
p.setcity(cityList);
xmlMapper2.enable(SerializationFeature.INDENT_OUTPUT);
String respPerson = xmlMapper2.writeValueAsString(p);
System.out.println(respPerson);
} catch (Exception e) {
e.printStackTrace();
}
}
This is the output that I get.
<Person><name>setattr</name><age>55</age><city><city><CityName>sfo</CityName></city><city><CityName>sjc</CityName></city><city><CityName>sea</CityName></city></city></Person>
Can you help me to understand why do I get two tags for city and how I can fix it?
I would like the output to be something like,
<Person><name>setattr</name><age>55</age><city><CityName>sfo</CityName><CityName>sjc</CityName><CityName>sea</CityName></city></Person>
You have a list of cities. Jackson is using 'city' for both the list itself and the members of the list. If you change the local name to 'cities', you might like the results better.
Unfortunately, this isn't the right answer. It appears, rather, that the right answer is provided https://stackoverflow.com/a/27144625/131433.
I try to save data to object user by gson but have an error:
java.lang.RuntimeException: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 911330 path $.assignedUser....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
at com.loopj.andro
User class is:
public class User {
#SerializedName("id")
int id;
#SerializedName("frontName")
String name;
#SerializedName("email")
String email;
#SerializedName("phoneNumber")
String phoneNumber;
#SerializedName("pesel")
String pesel;
#SerializedName("readableAdress")
String adress;
#SerializedName("avatar")
String avatar;
#SerializedName("city")
String city;
}
and code where I use gson:
User user = new User();
String response = new String(responseBody, "UTF-8");
Gson gson = new Gson();
user = gson.fromJson(response, User.class);
Problem is in the structure of the string response?
It seems that your JSON string is malformed. You can try this tool to validate it before parsing it with GSON.
https://jsonformatter.curiousconcept.com/
User Class:
public class UserData {
private int id;
private String name;
private String email;
private String phoneNumber;
private String pesel;
private String address;
private String avatar;
private String city;
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Now parse it like this:
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
Gson gson = new Gson();
response = gson.fromJson(br, User.class);