Java object:
public class Foo {
#JsonProperty("name")
private String name;
#JsonProperty("surname")
private String surname;
// getters + setters
}
JSON:
{
"meta":{
"code":200
},
"data":[
{
"name":"John",
"surname":"Smith"
}
]
}
API call:
return restTemplate.getForEntity(requestUrl, Foo[].class).getBody();
Is it possible to parse "data" array without creating an additional wrapper class? I tried adding the #JsonRootName("data") annotation on top of my Java class, but it did not work.
You can try with:
import org.json.*;
JSONObject obj = new JSONObject(" .... ");
String name = obj.getJSONObject("data").getString("name");
Related
I'm trying to get Java Object from JSON string that has inner arrays, there are pretty same questions, but none couldn't solve my problem. Now in console i get MethodPackage.JsonDeserialize#6580cfdd (I'm doing with objectmapper)
My aim is to get separately values in json to do some manupulations
below is my full code:
JSONstring:
{
"status": 1,
"message": "ok",
"sheduleCod": "NOST_A_Persons_m_noaccum",
"algorithms": [{
"cod": "No_st_alg_1",
"kcp": "U6000427",
"dtBeg": "2017-11-01 00:00:00",
"dtEnd": "2017-12-01 00:00:00"
}, {
"cod": "No_st_alg_2",
"kcp": "U6000427",
"dtBeg": "2017-11-01 00:00:00",
"dtEnd": "2017-12-01 00:00:00"
}, {
"cod": "No_st_alg_3",
"kcp": "U6000427",
"dtBeg": "2017-11-01 00:00:00",
"dtEnd": "2017-12-01 00:00:00"
}]
}
Main.class
String jsonString = response.toString();
JsonDeserialize deserialize = objectMapper.readValue(jsonString, JsonDeserialize.class);
System.out.println(deserialize);}
JsonDeserialize.class
public class JsonDeserialize {
private String status;
private String message;
private String sheduleCod;
private List<Algorithm> algorithms;
in JsonDeserialize.class
public class JsonDeserialize {
private String status;
private String message;
private String sheduleCod;
private List<Algorithm> algorithms;
public JsonDeserialize(String status, String message, String sheduleCod, List<Algorithm> algorithms) {
this.status = status;
this.message = message;
this.sheduleCod = sheduleCod;
this.algorithms = algorithms;
}
..... and then getters and setters
Algorithm.class
public class Algorithm {
private String cod;
private String kcp;
private String dtBeg;
private String dtEnd;
public Algorithm(String cod, String kcp, String dtBeg, String dtEnd) {
this.cod = cod;
this.kcp = kcp;
this.dtBeg = dtBeg;
this.dtEnd = dtEnd;
}
public Algorithm () {
}
The output MethodPackage.JsonDeserialize#6580cfdd means that you print the reference and not the values of the object.
To fix this problem override the toString method within the JsonDeserialize class like the following:
#Override
public String toString() {
String values = ""; // you could also use a StringBuilder here
values += "Status: " + status + "\n";
values += "Message: " + message + "\n";
// ....
return values;
}
or use:
System.out.println(deserialize.getStatus())
System.out.println(deserialize.getMessage());
// ...
If you are using Jackson or GSON, you you can just create POJOs that match the structure of the data and it will work automatically. Also, in those pojos you can either make the names of the properties be exactly the same as the JSON has or else use the jackson annotation to let you provide the JSON property name for each object property. But mainly i don't see any getters and setters for your POJOS that you did show, and most likely you do need those. Be carefeul that you name the properties using the right 'bean naming' conventions.
I'm starting using jackson json after Jaunt, but i can't understand some details in deserialization.
I have JSON response from server, here it is:
{
success: true,
stickers: [
{
id: "88899",
name: "",
img: ""
},
{
id: "13161",
name: "3DMAX",
img: ""
}
]
}
I have a Sticker class in my project
public class Sticker {
#JsonProperty("id")
private String id;
#JsonProperty("name")
private String name;
#JsonProperty("img")
private String imgUrl;
//getters and setters and constructors
}
I want to read this response and create a List of Stickers:
List(Sticker) stickerList;
**Another task (if it is possible with jackson tools), i want to create HashMap(String, Sticker) during deserilization instead of List(Sticker) **
How to do it easy and properly?
I have found a solution for List: I created class
public class StickerPage {
#JsonProperty("stickers")
private List<Sticker> stickerList;
public List<Sticker> getStickerList() {
return stickerList;
}
public void setStickerList(List<Sticker> stickerList) {
this.stickerList = stickerList;
}
}
And used it for this:
ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
StickerPage stickerPage = objectMapper.readValue(inputStream, StickerPage.class);
HashMap<String, Sticker> stickerHashMap = new HashMap<>();
for (Sticker sticker : stickerPage.getStickerList()) {
stickerHashMap.put(sticker.getName(), sticker);
}
But it looks weird i think, can you help me with this task?
I have the following json
{ "file": {"file": "foo.c", "owner": "user123"}
"methods": [{"name": "proc1", "value":"val"}, {"name":"proc2","value":"val2"}]
etc...
}
I know that I can do something like
class file{
public String file
public String owner
}
class methods{
public String name
public String value
}
and I can either call
File file= gson.fromJson(jsonInString, File.class);
methods[] array = gson.fromJson(jsonInString, methods[].class);
but what do I do if I need to handle a complex json that contains many objects all togther
I cannot specify gson.fromJson(jsonInString, ListOfClasses)
I normally follow this approach to get any complex classes converted from json to object. This approach works for almost everything like list, map etc. The idea is simple create holders for the complex classes and then create the classes. Give as much depth as much required. The trick is to match name in Json and your holders (and subclasses).
File Config:
class FileConfig{
public String file;
public String owner;
//define toString, getters and setters
}
Method Class:
class Method{
public String name;
public String value;
//define toString, getters and setters
}
Method Config:
class MethodConfig{
List<Method> methods = null;
//define toString, getters and setters
}
Holding the Config:
public class HolderConfig {
private FileConfig file = null;
private MethodConfig methods = null;
public FileConfig getFile() {
return file;
}
public void setFile(FileConfig file) {
this.file = file;
}
public MethodConfig getMethods() {
return file;
}
public void setMethods(MethodConfig methods) {
this.methods = methods;
}
}
Building the config:
public class HolderConfigBuilder {
public static HolderConfig build(JsonObject holderConfigJson) {
HolderConfig configHolderInstance = null;
Gson gsonInstance = null;
gsonInstance = new GsonBuilder().create();
configHolderInstance = gsonInstance.fromJson(holderConfigJson,HolderConfig.class);
return configHolderInstance;
}
}
Demo class:
public class App
{
public static void main( String[] args )
{
HolderConfig configHolderInstance = null;
FileConfig file = null;
configHolderInstance = HolderConfigBuilder.build(<Input Json>);
file = configHolderInstance.getFile();
System.out.println("The fileConfig is : "+file.toString());
}
}
Input Json:
{ "file": {"file": "foo.c", "owner": "user123"}
"methods": [
{"name": "proc1", "value":"val"},
{"name":"proc2","value":"val2"}
]
}
Note: Write the code to get Input JSON in your test code.
In this way whenever you add more elements to your JSON you have to create a separate class for that element and just add the element name same as in your json into the HolderConfig. You need not change rest of the code.
Hope it helps.
From the server comes the answer
{
"error":false,
"lessons":[
{
"id":1,
"discipline":"??????????",
"type":"LECTURE",
"comment":"no comments"
},
{
"id":2,
"discipline":"???. ??",
"type":"LECTURE",
"comment":"no comments"
}
]
}
How correctly read object "lessons", and add to List ?
Use a wrapper object and you could directly read it as Wrapper obj = new Gson().fromJson(data, Wrapper.class);
import java.util.List;
import com.google.gson.Gson;
class Wrapper {
boolean error;
List<Lesson> lessons;
//Getters & Setters
}
class Lesson {
String id;
String discipline;
String type;
String comment;
//Getters & Setters
}
public class GsonSample {
public static void main(String[] args) {
String data = "{\"error\":false,\"lessons\":[{\"id\":1,\"discipline\":\"??????????\",\"type\":\"LECTURE\",\"comment\":\"no comments\"},{\"id\":2,\"discipline\":\"???. ??\",\"type\":\"LECTURE\",\"comment\":\"no comments\"}]}";
Wrapper obj = new Gson().fromJson(data, Wrapper.class);
System.out.println(obj.getLessons());
}
}
JSONArray lessions = response.getJSONArray("lessons");
JSONObject obj1 = lessions.getJSONObject(1); // 1 is index of elemet of array
String id = Obj1.getString("id");
And Same for others
I want to use Gson to Deserialize my JSON into objects.
I've defined the appropriate classes, and some of those class' objects are included in other objects.
When trying to deserialize the whole JSON, I got null values, so I started breaking it apart.
I reached the point where all lower classes stand by them selves, but when trying to deserialize into an object that holds an instance of that smaller object - every thing returns as null.
My partial JSON:
{
"user_profile": {
"pk": 1,
"model": "vcb.userprofile",
"fields": {
"photo": "images/users/Screen_Shot_2013-03-18_at_5.24.13_PM.png",
"facebook_url": "https://google.com/facebook",
"site_name": "simple food",
"user": {
"pk": 1,
"model": "auth.user",
"fields": {
"first_name": "blue",
"last_name": "bla"
}
},
"site_url": "https://google.com/"
}
}
}
UserProfile Class:
public class UserProfile {
private int pk;
private String model;
private UPfields fields = new UPfields();//i tried with and without the "new"
}
UPfields Class:
public class UPfields {
private String photo;
private String facebook_url;
private String site_name;
private User user;
private String site_url;
}
User Class:
public class User {
private int pk;
private String model;
private Ufields fields;
}
Ufields Class:
public class Ufields {
private String first_name;
private String last_name;
}
In my main I call:
Gson gson = new Gson();
UserProfile temp = gson.fromJson(json, UserProfile.class);
So my temp object contain only null values.
I've tried changing the classes to static, and it doesn't work.
The UPfields object and all lower one work fine.
Any suggestions?
when I remove the
"{
"user_profile":"
and it's closing bracket, the deserialize to a user_profile object works.
In order to parse this json example you have to create auxiliary class, which will contain field named user_profile of type UserProfile:
public class UserProfileWrapper {
private UserProfile user_profile;
}
and parse this json string with this class:
UserProfileWrapper temp = gson.fromJson(json, UserProfileWrapper.class);
Gson starts by parsing the outermost object, which in your case has a single field, user_profile. Your UserProfile class doesn't have a user_profile field, so it can't deserialize it as an instance of that class. You should try to deserialize the value of the user_profile field instead.