Here is the JSON string return from API:
{"id":1,"bps_id":"C199","summary":{"as_of_date":"2017-06-20","bp_earned":0,"bp_balance":"199400","bp_redeemed":"600"},"bps_message":{"eng":"mobile testing message","chi":"mobile testing message chi"},"bps_image":"https:\/\/mydomain.com\/images\/eng\/promotion\/C199_MH.gif","error_message":{"eng":"","chi":""},"error_flags":""}
And I have created an object for this:
public class SummaryResponse {
String bps_id;
String bps_image;
String bps_message;
String as_of_date;
String bp_earned;
String bp_redeemed;
String bp_balance;
public String getBps_image() {
return bps_image;
}
public LangResponse getBps_message() {
return bps_message;
}
public String getAs_of_date() {
return as_of_date;
}
public String getBp_earned() {
return bp_earned;
}
public String getBp_redeemed() {
return bp_redeemed;
}
public String getBp_balance() {
return bp_balance;
}
}
It does not convert as expert, as there is some JSON object inside the string, how to convert that as well? Thanks for helping.
You can create like this,
public class SummaryResponse {
public String id;
public String bps_id;
public Summary summary;
public Message bps_message;
public String bps_image;
public Message error_message;
public String error_flags;
class Summary {
public String as_of_date;
public int bp_earned;
public String bp_balance;
public String bp_redeemed;
}
class Message {
public String eng;
public String chi;
}
}
you can call like this.
SummaryResponse summaryResponse = new Gson().fromJson([Your Json], SummaryResponse.class);
This a quick simple way to parse an array of Objects and also a single object it works for me when I am parsing json.
I believe it will only work as long as the json object is well formatted. I haven't experimented with a ill-formatted json object but that is because the api it request from was build by me, so I haven't had to worry about that
Gson gson = new Gson();
SummaryResponse[] data = gson.fromJson(jsonObj, SummaryResponse[].class);
Related
I'm having a null return using Gson.fromJson() and I don't understand why.
I'm calling an API that returns some data with this format:
{
"RealisedItems":{
"realisedItem":[
{
"actionItem1":1,
"actionItem2":"ITEM_ANSWER",
"actionItem3":"CREATE_ITEM",
"actionItem4":[
"XXXXXXX"
]
},
{
"actionItem1":2,
"actionItem2":"ITEM_ANSWER",
"actionItem3":"LINK_ITEM",
"actionItem5":"202007050000",
"actionItem4":[
"XXXXXXX"
]
}
]
}
}
Here's my objects to receive the data :
public class RealisedItems {
private List<RealisedItem> realisedItem = null;
public List<RealisedItem> getRealisedItem() {
return realisedItem;
}
public void setRealisedItem(List<RealisedItem> realisedItem) {
this.realisedItem = realisedItem;
}
}
And
public class RealisedItem {
private Long actionItem1;
private String actionItem2;
private String actionItem3;
private List<String> actionItem4 = null;
private String actionItem5;
public Long getActionItem1() {
return actionItem1;
}
public void setActionItem1(Long actionItem1) {
this.actionItem1 = actionItem1;
}
public String getActionItem2() {
return actionItem2;
}
public void setActionItem2(String actionItem2) {
this.actionItem2 = actionItem2;
}
public String getActionItem3() {
return actionItem3;
}
public void setActionItem3(String actionItem3) {
this.actionItem3 = actionItem3;
}
public List<String> getActionItem4() {
return actionItem4;
}
public void setActionItem4(List<String> actionItem4) {
this.actionItem4 = actionItem4;
}
public String getActionItem5() {
return actionItem5;
}
public void setActionItem5(String actionItem5) {
this.actionItem5 = actionItem5;
}
}
Using the debug mode, I can see by that the response object from this line : gson.fromJson(response, RealisedItems.class); contains the Json in String format that you can see above but my list is null after this. I'm using the same code for another response from a different service and I have my object filled with data.
From what I can see, in the fist "realisedItem" object, I have 4 items while in the second, I have 5. Can this cause this issue?
I tried to change the list to an array (RealisedItem[]) but it's not working either.
I also tried to use the #Expose with #SerializedName and changing Gson gson = new Gson(); to Gson gson = new GsonBuilder().create(); and Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); with the fifth item not having the #Expose annotation, but I'm still having my list null.
Can you please enlight me? Thanks!
Thanks to #Andreas, I realized I've made a mistake and used RealisedItems as root object. I just created a new object called ItemsOutput which contains RealisedItems field. I added a #SerializedName annotation to indicate it's called "RealisedItems" with an uppercase and changed my Gson.fromJson() call with the newly created object. It's working.
Thanks!
I'm trying to use the StringUtils.removeAll method to delete parts of a string and keep the other parts:
String locations = [{"code":"b","name":"Beavercreek"},{"code":"bj","name":"Beavercreek Juvenile"},...]
Here is my regex
StringUtils.removeAll(result.get("locations").toString(),"\\{\"code\":,\"name\":^[a-zA-Z0-9_.-]*$\"\"\\}");
It doesn't remove anything, I can't get the regex correct?
It looks like the string your trying to parse is JSON so I would recommend using a JSON parser. For completeness however, I'll give you a solution using a regex as well.
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public static void main(String[] args) throws Exception {
String locations = "[{\"code\":\"b\",\"name\":\"Beavercreek\"},{\"code\":\"bj\",\"name\":\"Beavercreek Juvenile\"}]";
// Parsing Using a JSON Parser (Recommended)
ObjectMapper jsonMapper = new ObjectMapper();
Model[] modelArray = jsonMapper.readValue(locations, Model[].class);
for(Model model : modelArray) {
System.out.println(model.toString());
}
// Parsing Using String.replaceAll with regex
locations = locations.replaceAll("\\{\"code\":", "");
locations = locations.replaceAll("\"name\":", "");
System.out.println(locations.replaceAll("\\}", ""));
}
static class Model {
private String code;
private String name;
public Model() { }
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return String.format("%s, %s", code, name);
}
}
}
Output:
// JSON Parsing
b, Beavercreek
bj, Beavercreek Juvenile
// REGEX Parsing
["b","Beavercreek","bj","Beavercreek Juvenile"]
I'm trying to convert a simple java object in JSON. I'm using google Gson library and it works, but I want a complete JSON object in this form:
{"Studente":[{ "nome":"John", "cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}]}
This is my class:
public class Studente {
private String nome;
private String cognome;
private String matricola;
private String dataNascita;
public Studente(){
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getMatricola() {
return matricola;
}
public void setMatricola(String matricola) {
this.matricola = matricola;
}
public String getDataNascita() {
return dataNascita;
}
public void setDataNascita(String dataNascita) {
this.dataNascita = dataNascita;
}
}
This is tester:
Studente x = new Studente();
x.setCognome("Doe");
x.setNome("Jhon");
x.setMatricola("0512");
x.setDataNascita("14/10/1991");
Gson gson = new Gson();
String toJson = gson.toJson(x, Studente.class);
System.out.println("ToJSON "+toJson);
I have this in toJson: {"nome":"Jhon","cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}
The Json that you are trying to achieve is not the representation of a single Studente object, it is the representation of an object containing a list of Studente objects, that has a single entry.
So, you would need to create that extra object that contains the list of Studente objects, add the one instance to the list, and then serialize the object containing the list.
There's one minor issue, though. You are essentially asking for the wrapper object's list to have a property name that starts with a capital letter. This can be done, but breaks Java coding conventions.
It is best to write a wrapper for Students list. like this:
import java.util.ArrayList;
public class StudentWrapper {
private ArrayList<Studente> studente;
public StudentWrapper() {
studente = new ArrayList<Studente>();
}
public void addStudent(Studente s){
studente.add(s);
}
}
Code to convert to JSON :
Studente x=new Studente();
x.setCognome("Doe");
x.setNome("Jhon");
x.setMatricola("0512");
x.setDataNascita("14/10/1991");
Gson gson=new Gson();
StudentWrapper studentWrapper = new StudentWrapper();
studentWrapper.addStudent(x);
String toJson=gson.toJson(studentWrapper, StudentWrapper.class);
System.out.println("ToJSON "+toJson);
The output will be like this. The way you want it.
ToJSON {"studente":[{"nome":"Jhon","cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}]}
I have a JSON object that looks like this
{
id:int,
tags: [
"string",
"string"
],
images: {
waveform_l:"url_to_image",
waveform_m:"url_to_image",
spectral_m:"url_to_image",
spectral_l:"url_to_image"
}
}
I'm trying to use retrofit to parse the JSON and create the interface. The problem that I have is that I get a null for the images urls. Everything else works, I am able to retrieve the id, the tags, but when I try to get the images they are all null.
I have a sound pojo that looks like this:
public class Sound {
private Integer id;
private List<String> tags = new ArrayList<String>();
private Images images;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Images getImages() {
return images;
}
public void setImages(Images images) {
this.images = images;
}
... setters and getter for tags as well
}
and I have a Images pojo that looks like this:
public class Images {
private String waveformL;
private String waveformM;
private String spectralM;
private String spectralL;
public String getWaveformL() {
return waveformL;
}
public void setWaveformL(String waveformL) {
this.waveformL = waveformL;
}
public String getWaveformM() {
return waveformM;
}
public void setWaveformM(String waveformM) {
this.waveformM = waveformM;
}
public String getSpectralM() {
return spectralM;
}
public void setSpectralM(String spectralM) {
this.spectralM = spectralM;
}
public String getSpectralL() {
return spectralL;
}
public void setSpectralL(String spectralL) {
this.spectralL = spectralL;
}
}
Whenever I try to call images.getWaveformM() it gives me a null pointer. Any ideas?
#SerializedName can also be used to solve this. It allows you to match the expected JSON format without having to declare your Class variable exactly the same way.
public class Images {
#SerializedName("waveform_l")
private String waveformL;
#SerializedName("waveform_m")
private String waveformM;
#SerializedName("spectral_m")
private String spectralM;
#SerializedName("spectral_l")
private String spectralL;
...
}
If the only differences from the JSON to your class variables are the snake/camel case then perhaps #njzk2 answer works better but in cases where there's more differences outside those bounds then #SerializeName can be your friend.
You possibly need this part:
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) will allow gson to automatically transform the snake case into camel case.
public class Images {
private String waveform_l;
private String waveform_m;
private String spectral_m;
private String spectral_m;
}
Key name should be same in model as in json other wise it won't recognise it else you haven't define it at GsonBuilder creation.Generate the getter setter for the same and you will be good to go
I just try to integrate with external webservice via JSON from Android. I receive following JSON format:
Data that i'm interested in is in "messages" branch.
To access data i'm using :
builder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
Gson gson = builder.create();
ClassToStore response = gson.fromJson(reader, ClassToStore.class);
where reader is a input stream from:
am = getInstrumentation().getContext().getAssets();
am.open("data.json");
Message structure looks like:
ClassToStore has all fields with the same names.
I get all objects but all of theme are null's
PLEASE HELP :(
My classToStore:
public static class ClassToStore implements Serializable {
private static final long serialVersionUID = -1463052486583654136L;
public String id ;
public String replied_to_id ;
public String sender_id ;
public String created_at ;
public String getId() {
return id;
}
public String getReplied_to_id() {
return replied_to_id;
}
public String getSender_id() {
return sender_id;
}
public String getCreated_at() {
return created_at;
}
}
You will need an extra class to match the outer object:
public class OuterObject {
List<ClassToStore> messages;
}
And then load it like this:
Gson gson = new Gson();
Type type = new TypeToken<List<OuterObject>>(){}.getType();
List<OuterObject> outerList = gson.fromJson(reader, type);
List<ClassToStore> listOfMessages = outerlist.get(0).messages;