Java Android FCM parse data to object - java

I want to parse json which I send to my phone. this is what I get :
In params I get two string
UPDATE_ROUTE
and
[{"card_id":"3a296050-b7dc-4f7b-a041-162817090520","t_tasks_e_dic_load_types_sj_id":132,"status_id":2,"eup":"86baeff7e","card_nr":"211","change_time":"2019-12-17T12:04:43.129Z"}]
this is my class :
public class FCMResponse{
#SerializedName("data")
private List<DataItem> data;
#SerializedName("type")
private String type;
}
I try do this :
FCMResponse fcm = g.fromJson("\"data\":"+updateResponse.getData(), FCMResponse.class);
but when I try parse this or try parse string to my java class I get :
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $

According to this response,
[{"card_id":"3a296050-b7dc-4f7b-a041-162817090520","t_tasks_e_dic_load_types_sj_id":132,"status_id":2,"eup":"86baeff7e","card_nr":"211","change_time":"2019-12-17T12:04:43.129Z"}]
your model class should be
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("card_id")
#Expose
private String cardId;
#SerializedName("t_tasks_e_dic_load_types_sj_id")
#Expose
private Integer tTasksEDicLoadTypesSjId;
#SerializedName("status_id")
#Expose
private Integer statusId;
#SerializedName("eup")
#Expose
private String eup;
#SerializedName("card_nr")
#Expose
private String cardNr;
#SerializedName("change_time")
#Expose
private String changeTime;
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public Integer getTTasksEDicLoadTypesSjId() {
return tTasksEDicLoadTypesSjId;
}
public void setTTasksEDicLoadTypesSjId(Integer tTasksEDicLoadTypesSjId) {
this.tTasksEDicLoadTypesSjId = tTasksEDicLoadTypesSjId;
}
public Integer getStatusId() {
return statusId;
}
public void setStatusId(Integer statusId) {
this.statusId = statusId;
}
public String getEup() {
return eup;
}
public void setEup(String eup) {
this.eup = eup;
}
public String getCardNr() {
return cardNr;
}
public void setCardNr(String cardNr) {
this.cardNr = cardNr;
}
public String getChangeTime() {
return changeTime;
}
public void setChangeTime(String changeTime) {
this.changeTime = changeTime;
}
#Override
public String toString() {
return "Example{" +
"cardId='" + cardId + '\'' +
", tTasksEDicLoadTypesSjId=" + tTasksEDicLoadTypesSjId +
", statusId=" + statusId +
", eup='" + eup + '\'' +
", cardNr='" + cardNr + '\'' +
", changeTime='" + changeTime + '\'' +
'}';
}
}
And you can fetch in class like,
Gson gson = new Gson();
Example[] examples = gson.fromJson(response, Example[].class);
Example example = examples[0];

Related

How do I get an array value instead of reference from ObjectMapper in Jackson?

I am trying to get a result from an API response and am able to map everything except for columnHeaders, which is an array of ColumnHeaders. I am instead getting a reference to an array. The code is below.
Response Class
public class Response {
#JsonProperty("searchApiFormatVersion")
private String searchApiFormatVersion;
#JsonProperty("searchName")
private String searchName;
#JsonProperty("description")
private String description;
#JsonProperty("columnHeaders")
private ColumnHeader[] columnHeaders;
public Response(String searchApiFormatVersion, String searchName, String description,
ColumnHeader[] columnHeaders) {
this.searchApiFormatVersion = searchApiFormatVersion;
this.searchName = searchName;
this.description = description;
this.columnHeaders = columnHeaders;
}
public Response(){
}
public String getSearchApiFormatVersion() {
return searchApiFormatVersion;
}
public void setSearchApiFormatVersion(String searchApiFormatVersion) {
this.searchApiFormatVersion = searchApiFormatVersion;
}
public String getSearchName() {
return searchName;
}
public void setSearchName(String searchName) {
this.searchName = searchName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ColumnHeader[] getColumnHeaders() {
return columnHeaders;
}
public void setColumnHeaders(ColumnHeader[] columnHeaders) {
this.columnHeaders = columnHeaders;
}
#Override
public String toString() {
return "Response{" +
"searchApiFormatVersion='" + searchApiFormatVersion + '\'' +
", searchName='" + searchName + '\'' +
", description='" + description + '\'' +
", totalRowCount=" + totalRowCount +
", returnedRowCount=" + returnedRowCount +
", startingReturnedRowNumber=" + startingReturnedRowNumber +
", basetype='" + basetype + '\'' +
", columnCount=" + columnCount +
", columnHeaders=" + columnHeaders +
'}';
}
}
ColumnHeader class
public class ColumnHeader {
#JsonProperty("text")
private String text;
#JsonProperty("dataType")
private String dataType;
#JsonProperty("hierarchy")
private int hierarchy;
#JsonProperty("parentName")
private String parentName;
#JsonProperty("isEntity")
private Boolean isEntity;
#JsonProperty("isEset")
private Boolean isEset;
public ColumnHeader(String text, String dataType, int hierarchy, String parentName, Boolean isEntity, Boolean isEset) {
this.text = text;
this.dataType = dataType;
this.hierarchy = hierarchy;
this.parentName = parentName;
this.isEntity = isEntity;
this.isEset = isEset;
}
public ColumnHeader(){
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public int getHierarchy() {
return hierarchy;
}
public void setHierarchy(int hierarchy) {
this.hierarchy = hierarchy;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Boolean getEntity() {
return isEntity;
}
public void setEntity(Boolean entity) {
isEntity = entity;
}
public Boolean getEset() {
return isEset;
}
public void setEset(Boolean eset) {
isEset = eset;
}
#Override
public String toString() {
return "ColumnHeader{" +
"text='" + text + '\'' +
", dataType='" + dataType + '\'' +
", hierarchy=" + hierarchy +
", parentName='" + parentName + '\'' +
", isEntity=" + isEntity +
", isEset=" + isEset +
'}';
}
}
Service Class
public class BudgetEffortResponseService {
Logger logger = LoggerFactory.getLogger(Response.class);
public Response getResponseFromStringJsonApiResponse(String stringJsonResponse) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper(); //Used to map objects from JSON values specified in Award under #JsonProperty annotation
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JSONObject stringJsonResponseTurnedIntoJsonObject = new JSONObject(stringJsonResponse);
logger.info("stringJsonResponseTurnedIntoJsonObject: " + stringJsonResponseTurnedIntoJsonObject);
return objectMapper.readValue(stringJsonResponseTurnedIntoJsonObject.toString(), Response.class);
}
}
Main Class
#SpringBootApplication
public class EtlApplication {
public static final String API_USERNAME = System.getenv("API_USERNAME");
public static final String API_PASSWORD = System.getenv("API_PASSWORD");
public static final String API_PREFIX = System.getenv("API_PREFIX");
public static final String API_PATH = System.getenv("API_PATH");
public static void main(String[] args) throws URISyntaxException, JsonProcessingException {
Logger logger = LoggerFactory.getLogger(EtlApplication.class);
logger.info("--------------------Starting process--------------------");
AwardRepository awardRepository = new AwardRepository();
AwardService awardService = new AwardService();
ApiResponseRowService apiResponseRowService = new ApiResponseRowService();
ApiResponseRepository apiResponseRepository = new ApiResponseRepository();
BudgetEffortResponseService budgetEffortResponseService = new BudgetEffortResponseService();
Date startDateForApiPull = new GregorianCalendar(2023, Calendar.FEBRUARY, 1).getTime();
Date endDateForApiPull = new GregorianCalendar(2023, Calendar.FEBRUARY, 2).getTime();
logger.info("============Starting BudgetEffort API pull from Huron===============");
HttpResponse<String> budgetEffortHttpResponse = apiResponseRepository.getHttpResponseFromApi(startDateForApiPull,
endDateForApiPull, 1, -1, API_PREFIX, API_PATH,
API_USERNAME, API_PASSWORD);
logger.info("BudgetEffortHttpResponse: " + budgetEffortHttpResponse);
logger.info("============End of BudgetEffort API pull from Huron===============");
//Get body of http response string
String budgetEffortResponseString = budgetEffortHttpResponse.body();
logger.info("BudgetEffortResponseString: " + budgetEffortResponseString);
Response budgetEffortResponse = budgetEffortResponseService.getResponseFromStringJsonApiResponse(budgetEffortResponseString);
logger.info("BudgetEffortResponse: " + budgetEffortResponse);
logger.info("--------------------End of process--------------------");
}
}
The response. I'm noticing that I'm getting the reference to the array for columnHeaders and not the values. How would I get the values? Thank you.
BudgetEffortResponse: Response{searchApiFormatVersion='1.0', searchName='Personnel Details for Authorized allocations on Active Awards', description='', columnHeaders=[Lcom.example.etl.entity.budgetEffort.ColumnHeader;#7a7471ce}
The response you get is ok. And also the Array is good. The line
logger.info("BudgetEffortResponse: " + budgetEffortResponse);
uses an indirect cast to String of the Object budgetEffortResponse. In this case all toString() methods of the objects are called. What you need to do in order to print out the Objects is to implement/add the toString() method in the class com.example.etl.entity.budgetEffort.ColumnHeader
Update:
As the toString method is already implemented, the above is partially wrong. But there is a way to use a setting of the ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
// pretty print
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(budgetEffortResponse);
logger.info("BudgetEffortResponse: " + json);

How to get the covid info of a country with java, JSON

I am making a java file in which you enter the country and then it shows you the covid-19 info of that country. The site which I am using is https://covid19.mathdro.id/api/countries/
here i want it such that the user enter the country and it adds the countries name to the website eg if the user entered India it should do this
https://covid19.mathdro.id/api/countries/India
Any help would be neccessary, Thanks
You can use Retrofit to call the APIs
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.Response;
public class Retrofit_Example {
public static void main(String[] args) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://covid19.mathdro.id/")
.addConverterFactory(GsonConverterFactory.create())
.client(client.build())
.build();
Service service = retrofit.create(Service.class);
Call<Response1> responseCall = service.getData("India");
try {
Response<Response1> response = responseCall.execute();
Response1 apiResponse = response.body();
System.out.println(apiResponse);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You will have to create POJOs from the JSON response coming from the api first and also the retrofit client.
POJO for respone
public class Response1 {
private Confirmed confirmed;
private Deaths deaths;
private String lastUpdate;
private Recovered recovered;
public Confirmed getConfirmed() {
return confirmed;
}
public void setConfirmed(Confirmed confirmed) {
this.confirmed = confirmed;
}
public Deaths getDeaths() {
return deaths;
}
public void setDeaths(Deaths deaths) {
this.deaths = deaths;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Recovered getRecovered() {
return recovered;
}
public void setRecovered(Recovered recovered) {
this.recovered = recovered;
}
#Override
public String toString() {
return "Response1{" +
"confirmed=" + confirmed +
", deaths=" + deaths +
", lastUpdate='" + lastUpdate + '\'' +
", recovered=" + recovered +
'}';
}
}
public class Recovered {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Recovered{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
public class Deaths {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Deaths{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
public class Confirmed {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Confirmed{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
Retrofit Client
public interface Service {
#GET("/api/countries/{country}")
public Call<Response1> getData(#Path("country")String country);
}

Reading JSON - Retrofit - Android Studio

i really ned help with this. Im not being able to read the JSON and i dont know what im doing wrong.
I will drop my code here.
I have this Json
{
"id": "288",
"name": "Tarjeta Shopping",
"secure_thumbnail": "https://www.mercadopago.com/org-img/MP3/API/logos/288.gif",
"thumbnail": "http://img.mlstatic.com/org-img/MP3/API/logos/288.gif",
"processing_mode": "aggregator",
"merchant_account_id": null
}
This is my class that should represent that JSON
public class Tarjeta {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("secure_thumbnail")
#Expose
private String secureThumbnail;
#SerializedName("thumbnail")
#Expose
private String thumbnail;
#SerializedName("processing_mode")
#Expose
private String processingMode;
#SerializedName("merchant_account_id")
#Expose
private Object merchantAccountId;
public Tarjeta() {
}
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 String getSecureThumbnail() {
return secureThumbnail;
}
public void setSecureThumbnail(String secureThumbnail) {
this.secureThumbnail = secureThumbnail;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getProcessingMode() {
return processingMode;
}
public void setProcessingMode(String processingMode) {
this.processingMode = processingMode;
}
public Object getMerchantAccountId() {
return merchantAccountId;
}
public void setMerchantAccountId(Object merchantAccountId) {
this.merchantAccountId = merchantAccountId;
}
#Override
public String toString() {
return "Tarjeta{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", secureThumbnail='" + secureThumbnail + '\'' +
", thumbnail='" + thumbnail + '\'' +
", processingMode='" + processingMode + '\'' +
", merchantAccountId=" + merchantAccountId +
'}';
}
}
this is my GET method
#GET("payment_methods/card_issuers")
Call<Tarjeta> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);
And this is where i try to read it.
botonTest2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Test boton 2 clickeado");
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ServicePago servicePago = retrofit.create(ServicePago.class);
Call<Tarjeta> contenedorTarjetaCall = servicePago.getTarjetas2(apiKey,"visa");
contenedorTarjetaCall.enqueue(new Callback<Tarjeta>() {
#Override
public void onResponse(Call<Tarjeta> call, Response<Tarjeta> response) {
Toast.makeText(MainActivity.this, "BIEN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Tarjeta> call, Throwable t) {
Toast.makeText(MainActivity.this, "ALGO SALIO MAL", Toast.LENGTH_SHORT).show();
}
});
}
});
Im habing this error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
I think my class is correctly modelated, im completly lost.
since you did not post your entire JSON I'm going to answer with a rough idea hope it helps.
the error states that the received JSON is not a Tarjeta but an array of Tarjeta. so to fix it I guess you just have to wrap your response in a list type. so it goes something like this:
#GET("payment_methods/card_issuers")
Call<List<Tarjeta>> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);

How do I parse this JSON response into POJO

I have the following Test class:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibm.cio.cloud.cost.model.ElasticResponse;
import com.jayway.jsonpath.JsonPath;
#JsonIgnoreProperties(ignoreUnknown = true)
public class TestJSONPaths {
private static final String json = "{\"hits\":{\"total\":1,\"hits\":[{\"_id\":\"oEE4j2QBXCNPxFWHqq3i\",\"_score\":1.0,\"_source\":{\"status\":\"SUCCESSFUL\",\"reason\":\"OK, Single ACTIVE status can process\"}}]}}";
public static void main(String[] args) {
List<String> strippedJSON = JsonPath.read(json, "$.hits.hits._source");
ElasticResponse response = null;
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
try {
System.out.println("From this json string:" + strippedJSON + "\n");
response = mapper.readValue(strippedJSON.toString(), ElasticResponse.class);
System.out.println("ElasticDocument=" + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getDocuments()));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is the ElasticResponse class def:
public class ElasticResponse {
private List<ElasticDocument> documents;
public List<ElasticDocument> getDocuments() {
return documents;
}
public void setDocuments(List<ElasticDocument> documents) {
this.documents = documents;
}
}
public class ElasticDocument {
private String _id;
private String status;
private String reason;
... getters/setters
}
I'm trying to get a ElasticDocument object mapped from the JSON given but it's throwing the following errors below. I'm attempting to filtered out the JSON to simply be: [{_source document values }]. This error occurs on the very first line in the Main class. How can I map this Json?
[DEBUG] Evaluating path: $['hits']['hits']['_source']
Exception in thread "main" com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['_source'] in path $['hits']['hits'] but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:71)
at com.jayway.jsonpath.internal.path.PathToken.handleObjectProperty(PathToken.java:81)
at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:79)
at com.jayway.jsonpath.internal.path.PathToken.handleObjectProperty(PathToken.java:81)
at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:79)
at com.jayway.jsonpath.internal.path.RootPathToken.evaluate(RootPathToken.java:62)
at com.jayway.jsonpath.internal.path.CompiledPath.evaluate(CompiledPath.java:53)
at com.jayway.jsonpath.internal.path.CompiledPath.evaluate(CompiledPath.java:61)
at com.jayway.jsonpath.JsonPath.read(JsonPath.java:187)
at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:102)
at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:89)
at com.jayway.jsonpath.JsonPath.read(JsonPath.java:502)
at com.ibm.cio.cloud.cost.TestJSONPaths.main(TestJSONPaths.java:18)
The exception is due to the jsonpath returning an array instead of an object, so if you fix the jsonpath to look like this:
$.hits.hits[*]._source
Then it will evaluate properly. However, this probably still doesn't do what you want it to do.. The JsonPath.read() will deserialise the JSON for you. But you have to watch out with this:
public class Test {
private static final String json = "{\"hits\":{\"total\":1,\"hits\":[{\"_id\":\"oEE4j2QBXCNPxFWHqq3i\",\"_score\":1.0,\"_source\":{\"status\":\"SUCCESSFUL\",\"reason\":\"OK, Single ACTIVE status can process\"}}]}}";
public static void main(String[] args) {
List<ElasticDocument> docs = JsonPath.read(json, "$.hits.hits[*]._source");
System.out.println("elasticDoc: " + docs.get(0));
}
public static class ElasticDocument {
public String _id;
public String status;
public String reason;
#Override
public String toString() {
return "ElasticDocument{" +
"_id='" + _id + '\'' +
", status='" + status + '\'' +
", reason='" + reason + '\'' +
'}';
}
}
}
Looks like it works, however the docs List is now actually a List of Maps. Apparently It's possible to register JsonPath with Jackson but I can't make it work
Alternatively you can use Jackson to deserialise the JSON, then you should create an object model that matches the json structure and then you can use the ObjectMapper to do the deserialisation
public class Test {
private static final String json = "{\"hits\":{\"total\":1,\"hits\":[{\"_id\":\"oEE4j2QBXCNPxFWHqq3i\",\"_score\":1.0,\"_source\":{\"status\":\"SUCCESSFUL\",\"reason\":\"OK, Single ACTIVE status can process\"}}]}}";
public static void main(String[] args) {
System.out.println("From this json string:" + json + "\n");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
try {
HitsResource hitsResource = mapper.readValue(json, HitsResource.class);
System.out.println("jackson elasticDoc: " + hitsResource.hitsParent.hits.get(0).source);
} catch (Exception e) {
e.printStackTrace();
}
}
public static class HitsResource {
#JsonProperty("hits")
public HitsParent hitsParent;
#Override
public String toString() {
return "HitsResource{" +
"hitsParent=" + hitsParent +
'}';
}
}
public static class HitsParent {
#JsonProperty("total")
public Long total;
#JsonProperty("hits")
public List<Hits> hits;
#Override
public String toString() {
return "HitsParent{" +
"total=" + total +
", hits=" + hits +
'}';
}
}
public static class Hits {
#JsonProperty("_id")
public String id;
#JsonProperty("_score")
public BigDecimal score;
#JsonProperty("_source")
public ElasticDocument source;
#Override
public String toString() {
return "Hits{" +
"id='" + id + '\'' +
", score=" + score +
", source=" + source +
'}';
}
}
public static class ElasticDocument {
#JsonProperty("_id")
public String _id;
#JsonProperty("status")
public String status;
#JsonProperty("reason")
public String reason;
#Override
public String toString() {
return "ElasticDocument{" +
"_id='" + _id + '\'' +
", status='" + status + '\'' +
", reason='" + reason + '\'' +
'}';
}
}
}

How to parse JSON with Jackson that starts with "["

My string is like this:
[{"trends":[{"name":"#Happy16thPoniGoyangLimitedEditionJKT48","url":"http:\/\/twitter.com\/search?q=%23Happy16thPoniGoyangLimitedEditionJKT48","promoted_content":null,"query":"%23Happy16thPoniGoyangLimitedEditionJKT48","events":null},{"name":"#SemihVAROLTAYFAileHaftaSonuTakibi","url":"http:\/\/twitter.com\/search?q=%23SemihVAROLTAYFAileHaftaSonuTakibi","promoted_content":null,"query":"%23SemihVAROLTAYFAileHaftaSonuTakibi","events":null},{"name":"#JeeveTeriJodi","url":"http:\/\/twitter.com\/search?q=%23JeeveTeriJodi","promoted_content":null,"query":"%23JeeveTeriJodi","events":null},{"name":"#Tolga\u00D6\u011F\u00FCt\u0130leTakiple\u015Fme","url":"http:\/\/twitter.com\/search?q=%23Tolga%C3%96%C4%9F%C3%BCt%C4%B0leTakiple%C5%9Fme","promoted_content":null,"query":"%23Tolga%C3%96%C4%9F%C3%BCt%C4%B0leTakiple%C5%9Fme","events":null},{"name":"#CNEnjoyMondayyy","url":"http:\/\/twitter.com\/search?q=%23CNEnjoyMondayyy","promoted_content":null,"query":"%23CNEnjoyMondayyy","events":null},{"name":"Medha Patkar","url":"http:\/\/twitter.com\/search?q=%22Medha+Patkar%22","promoted_content":null,"query":"%22Medha+Patkar%22","events":null},{"name":"Asaram Bapuji","url":"http:\/\/twitter.com\/search?q=%22Asaram+Bapuji%22","promoted_content":null,"query":"%22Asaram+Bapuji%22","events":null},{"name":"Tune Talk","url":"http:\/\/twitter.com\/search?q=%22Tune+Talk%22","promoted_content":null,"query":"%22Tune+Talk%22","events":null},{"name":"Golden Globes 2014","url":"http:\/\/twitter.com\/search?q=%22Golden+Globes+2014%22","promoted_content":null,"query":"%22Golden+Globes+2014%22","events":null},{"name":"Game of Thrones Season 4","url":"http:\/\/twitter.com\/search?q=%22Game+of+Thrones+Season+4%22","promoted_content":null,"query":"%22Game+of+Thrones+Season+4%22","events":null}],"as_of":"2014-01-13T09:59:22Z","created_at":"2014-01-13T09:07:24Z","locations":[{"name":"Worldwide","woeid":1}]}]
I can parse this json string when I remove "[" and "]" from first and last character by following code:
private TrendTags getTrendTagsJSON(String jsonString) {
TrendTags trendTags = null;
jsonString = jsonString.substring(1, jsonString.length()-1);
try {
//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//convert json string to object
trendTags = objectMapper.readValue(jsonString, TrendTags.class);
System.out.println(trendTags);
} catch (JsonParseException e) {
System.out.println(e.getMessage());
} catch (JsonMappingException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
return trendTags;
}
And my TrendsTag class is this:
public class TrendTags {
#JsonProperty("trends")
private Trend[] trend;
#JsonProperty("locations")
private TrendLocation[] trendLocation;
#Override
public String toString() {
return "TrendTags{" +
"trend=" + Arrays.toString(trend) +
", trendLocation=" + Arrays.toString(trendLocation) +
'}';
}
public Trend[] getTrend() {
return trend;
}
public void setTrend(Trend[] trend) {
this.trend = trend;
}
public TrendLocation[] getTrendLocation() {
return trendLocation;
}
public void setTrendLocation(TrendLocation[] trendLocation) {
this.trendLocation = trendLocation;
}
/************************
* Trend item class *
************************/
public static class Trend {
private String name;
private String url;
private String query;
#Override
public String toString() {
return "Trend {" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", query='" + query + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
}
/************************
* Trend location class *
************************/
public static class TrendLocation {
private String name;
private int woeid;
#Override
public String toString() {
return "TrendLocation{" +
"name='" + name + '\'' +
", woeid=" + woeid +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWoeid() {
return woeid;
}
public void setWoeid(int woeid) {
this.woeid = woeid;
}
}
}
Since I have one object in array so it's possible to remove "[" and "]" from first and last chatacter. But this is not the solution.
My question is how to parse the json string with "[" and "]" characters? There should be a simple solution but I cannot find it. Thanks
Your JSON represents an array of your TrendTags objects. You're attempting to parse it as if it represented a single TrendTags object.
Get rid of all that code trying to modify the JSON, and just do:
TrendTags[] trendTags =
objectMapper.readValue(jsonString, TrendTags[].class);
That said, using a List is generally better;
List<TrendTags> trendTags =
objectMapper.readValue(jsonString, new TypeReference<List<TrendTags>>(){});

Categories