Converting String containing Json to gSonObject - java

I have a string that contains the following Json data
[{"date":"11/8/2014","auther":"nirav kalola","description":"json object parsing using gson library is easy","post_name":"json object parsing"},{"date":"12/8/2014","auther":"nirav kalola","description":"json array parsing using gson library","post_name":"json array parsing"},{"date":"17/8/2014","auther":"nirav kalola","description":"store json file in assets folder and get data when required","post_name":"json parsing from assets folder"}]
i want to convert it to gSon
i tried following code
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
//etResponse.setText(result);
try {
Type listType = new TypeToken<ArrayList<BeanPost>>() {
}.getType();
ArrayList<BeanPost> beanPostArrayList = new GsonBuilder().create().fromJson(result, listType);
// Above Line gives error
// JsonDeserializer could not Deserialize the object
StringBuffer postList = new StringBuffer();
for (BeanPost post : beanPostArrayList) {
postList.append("\n title: " + post.getPost_name() +
"\n auther: " + post.getAuther() +
"\n date: " + post.getDate() +
"\n description: " + post.getDescription() + "\n\n");
}
}
catch(Exception e2)
{
String msg=e2.getLocalizedMessage();
e2.printStackTrace();
}
}
BeanPost.java Class is as follows
package com.jobwork.mujahidniaz.ws2;
/**
* Created by Mujahid Niaz on 06/09/2016.
*/
import com.google.gson.annotations.SerializedName;
public class BeanPost {
#SerializedName("post_name")
private String post_name;
#SerializedName("auther")
private String auther;
#SerializedName("date")
private String date;
#SerializedName("description")
private String description;
public BeanPost(String post_name, String auther, String date, String description) {
this.post_name = post_name;
this.auther = auther;
this.date = date;
this.description = description;
}
public String getPost_name() {
return post_name;
}
public void setPost_name(String post_name) {
this.post_name = post_name;
}
public String getAuther() {
return auther;
}
public void setAuther(String auther) {
this.auther = auther;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I have tried a lot of search on google but could not find the Answer please help me with that.

(Untested code)
first you must create your empty public constructor from your BeanPost.java since you have custom constructor.
public BeanPost(){}
Gson gson = new Gson;
List<BeanPost> myBPost = gson.fromJson(result, List<BeanPost.class>); //i assume that result is your json string
now you're got to with your for each to get the value. Hope it helps

Related

Android POJO class check if particular key contains value as Boolean or arraylist

I have JsonArraylist in which there are multiple jsonobjects.In one of jsonObject json key contains Boolean value and on other Jsonobject the same key contain ArrayList.
How to check in POJO class if key contains ArrayList or boolean value as i am getting error:
W/System.err: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BOOLEAN at line 1 column 1927 path $1.tags
The Json is:
My POJO class is :
public class Posts implements Serializable
String id;
String title;
boolean mIsBookmark;
ArrayList<WebTags>tags;
public ArrayList<WebTags> getTags() {
return tags;
}
public void setTags(ArrayList<WebTags> tags) {
this.tags = tags;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public boolean isBookmark() {
return mIsBookmark;
}
public void setBookmark(boolean mIsBookmark) {
this.mIsBookmark = mIsBookmark;
}
#Override
public String toString() {
return "Webapps_post{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", date='" + date + '\'' +
", tags='"+ tags+'\'' +
'}';
}
public class WebTags implements Serializable
{
String term_id;
String name;
public String getTerm_id() {
return term_id;
}
public void setTerm_id(String term_id) {
this.term_id = term_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString()
{
return "WebTags{"+
"term_id='" + term_id + '\'' +
", name='" + name + '\'' +
'}';
}}
}
The TypeAdapter is exactly what you are looking for. To summarize you can add a custom conversion logic for a user defined datatype such as a class and the Gson serializer/deserializer is smart enough to do it based on the return type of the conversion methods
An example for the usage can be found here
You would need to create a custom deserializer for class Posts like below:
class PostsDeserializer : JsonDeserializer<Posts> {
#Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Posts {
val finalResult = Posts()
// manually set all elements (except 'tags') to finalResult object.
//...
// set tags element now
val tagsElement = json.asJsonObject.get("tags")
if(tagsElement?.isJsonArray == true) {
finalResult.tags = context.deserialize(tagsElement, WebTags::class.java)
} else {
finalResult.tags = emptyList()
}
return finalResult
}
}
The above code will tell the GSON library what to map when the tags field is an array or when the tags field is a boolean.

Unable to parse JSON with Jackson (mapping doesn't work)

I am trying to use Jackson to parse sample json as demonstrated below. However, I the parsing doesn't work (fails without any exceptions - as I get an empty string for event.getAccountId(); What could I be doing wrong?
Thanks!
ObjectMapper om = new ObjectMapper();
String json = "{\"_procurementEvent\" : [{ \"accountId\" : \"3243234\",\"procurementType\" : \"view\"," +
"\"_procurementSubType\" : \"Standard Connector\",\"_quantity\" : \"4\", \"_pricePerMonth\" : \"100.00\"" +
",\"_annualPrice\" : \"1200.00\"}]}";
ProcurementEvent event = om.readValue(json, ProcurementEvent.class);
event.getAccountId(); // returns null
#JsonIgnoreProperties(ignoreUnknown = true)
private static class ProcurementEvent {
private String _accountId;
private String _procurementType;
private String _quantity;
private String _pricePerMonth;
private String _annualPrice;
#JsonProperty("accountId")
public String getAccountId() {
return _accountId;
}
public void setAccountId(String accountId) {
_accountId = accountId;
}
#JsonProperty("procurementType")
public String getProcurementType() {
return _procurementType;
}
public void setProcurementType(String procurementType) {
_procurementType = procurementType;
}
#JsonProperty("_quantity")
public String getQuantity() {
return _quantity;
}
public void setQuantity(String quantity) {
_quantity = quantity;
}
#JsonProperty("_pricePerMonth")
public String getPricePerMonth() {
return _pricePerMonth;
}
public void setPricePerMonth(String pricePerMonth) {
_pricePerMonth = pricePerMonth;
}
#JsonProperty("_annualPrice")
public String getAnnualPrice() {
return _annualPrice;
}
public void setAnnualPrice(String annualPrice) {
_annualPrice = annualPrice;
}
}
In the question, try the following approach:
class ProcurementEvents {
private List<ProcurementEvent> _procurementEvent; // + annotations like #JsonIgnoreProperties, getters/ setters, etc.
}
// json from your example
ProcurementEvents events = om.readValue(json, ProcurementEvents.class);
events.get(0).getAccountId();

how to make retrofit POJO class for this Json

here is the json form that i try to make pojo class for it
[{"ID":"1",
"SectionName":""
,"Title":"testosss"}
,{"ID":"2"
,"SectionName":"",
"Title":"test"}]
i have one array with list of object what should i do to make pojo class in this case ?
Generate pojo class using jsonschema2pojo
import java.util.HashMap;
import java.util.Map;
public class Example {
private String iD;
private String sectionName;
private String title;
public Example(){
}
public Example(String id,String sectionName,String title){
this.iD = id;
this.sectionName = sectionName;
this.title = title;
}
public String getID() {
return iD;
}
public void setID(String iD) {
this.iD = iD;
}
public String getSectionName() {
return sectionName;
}
public void setSectionName(String sectionName) {
this.sectionName = sectionName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
whenever you have multiple jsonArray value in your json data, we need to store all data in ArrayList. here i have make some code for you i hope might be helpful you.
Your json data
String jsonDemo = "[{\"ID\":\"1\",\n" +
"\"SectionName\":\"\"\n" +
",\"Title\":\"testosss\"}\n" +
",{\"ID\":\"2\"\n" +
",\"SectionName\":\"\",\n" +
"\"Title\":\"test\"}]";
for get josn data and store in ArrayList with Example pojo class
create ArrayList class with pojo model class
ArrayList<Example> arrayList = new ArrayList<>();
json parsing and store each data in arraylist
try {
JSONArray jsonArray = new JSONArray(jsonDemo);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String ID = jsonObject.getString("ID");
String sectionName = jsonObject.getString("SectionName");
String title = jsonObject.getString("Title");
arrayList.add(new Example(ID,sectionName,title));
}
} catch (JSONException e) {
e.printStackTrace();
}
Retrieve all json data
if(arrayList.size()>0){
for(int i=0;i<arrayList.size();i++){
Example example = arrayList.get(i);
Log.d("Example","ID : " + example.getID());
Log.d("Example","getSectionName : " + example.getSectionName());
Log.d("Example","getTitle : " + example.getTitle());
}
}

Convert JSON array to Java Class Object List

I have a JSON string that comes from a WFC service. When I try to convert JSON array into List object, I've got the following error :
".JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: java.io.StringReader#41f27f18; line: 1, column: 1]"
The Java class (Card Class):
public class Card {
public String ID;
public String CompanyID;
public String CompanyName;
public String FiscalCode;
public String Limit;
public String StateID;
public String CardState;
public String Deleted;
public String Sold;
public String StartDate;
public String InvoiceStartDate;
public String Quantity;
public String Value;
public String CardTypeID;
public String CardType;
public String SoldChanged;
public String DriverName;
public String VehiclePlateNumber;
public String VehicleID;
public String Discount;
public String ContractID;
public String DiscountPerMonth;
public String ProductID;
public String ProductStateID;
public String Mail;
public String WithoutLimit;
public String ContractSold;
public String ContractLimit;
public String NumberOfTransactions;
public String DriverNameOnly;
public String DriverSurnameOnly;
}
The Java code to deserialize :
strResponse = responseHandler.handleResponse(response);
if (strResponse.contains("Credit") || strResponse.contains("Debit")) {
ObjectMapper mapper = new ObjectMapper();
strResponse= strResponse.replace("\"GetCardsResult\":", "");
userCards = mapper.readValue(strResponse, mapper.getTypeFactory().constructCollectionType(List.class, Card.class));
}
The JSON string:
{ "GetCardsResult":"[{\"ID\":3,\"CompanyID\":1155,\"CompanyName\":\"test\",\"FiscalCode\":null,\"Code\":\"1423127205\",\"Limit\":0.000,\"StateID\":1,\"CardState\":\"Activ\",\"Deleted\":false,\"Sold\":0.000,\"StartDate\":\"\/Date(1412974800000+0300)\/\",\"InvoiceStartDate\":\"\/Date(-62135596800000+0200)\/\",\"Quantity\":null,\"Value\":0.0,\"CardTypeID\":1,\"CardType\":\"Credit\",\"SoldChanged\":false,\"DriverName\":\"\",\"VehiclePlateNumber\":\"B 222 ART\",\"VehicleID\":null,\"Discount\":null,\"ContractID\":15,\"DiscountPerMonth\":null,\"ProductID\":null,\"ProductStateID\":null,\"Mail\":\"\",\"WithoutLimit\":true,\"ContractSold\":null,\"ContractLimit\":null,\"NumberOfTransactions\":null,\"DriverNameOnly\":null,\"DriverSurnameOnly\":null},{\"ID\":2881,\"CompanyID\":1155,\"CompanyName\":\"test\",\"FiscalCode\":null,\"Code\":\"test0000\",\"Limit\":125.000,\"StateID\":1,\"CardState\":\"Activ\",\"Deleted\":false,\"Sold\":132.330,\"StartDate\":\"\/Date(1436130000000+0300)\/\",\"InvoiceStartDate\":\"\/Date(-62135596800000+0200)\/\",\"Quantity\":null,\"Value\":0.0,\"CardTypeID\":1,\"CardType\":\"Credit\",\"SoldChanged\":false,\"DriverName\":\"aaa aaa\",\"VehiclePlateNumber\":\"aaa\",\"VehicleID\":null,\"Discount\":null,\"ContractID\":15,\"DiscountPerMonth\":null,\"ProductID\":null,\"ProductStateID\":null,\"Mail\":\"\",\"WithoutLimit\":true,\"ContractSold\":null,\"ContractLimit\":null,\"NumberOfTransactions\":null,\"DriverNameOnly\":null,\"DriverSurnameOnly\":null}]" }
Thanks in advance!
Try this:
try {
JSONObject jsonObject = null;
yourJSONString.replace("\\", "");
jsonObject = new JSONObject(yourJSONString);
String newJSONString = jsonObject.get("GetCardsResult").toString();
JSONArray jsonMainArr = new JSONArray(newJSONString);
//now just loop the json Array
for (int i = 0; i < jsonMainArr.length(); ++i) {
JSONObject rec = jsonMainArr.getJSONObject(i);
card.set_id(rec.get("ID").toString());
//....
}
} catch (JSONException e) {
e.printStackTrace();
}
Try to use GSON its very efficient and easy to implement, As example below will be your POJO class.
public class Post {
#SerializedName("id")
public long ID;
public String title;
public String author;
public String url;
#SerializedName("date")
public Date dateCreated;
public String body;
public List tags;
public Post() {
}
}
//Tag.java
public class Tag {
public String name;
public String url;
public Tag() {
}
}
And this will how you parse your JSON string to Object Class,
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Post> posts = new ArrayList<Post>();
posts = Arrays.asList(gson.fromJson(reader, Post[].class));
content.close();
What do you pass to the mapper - string before or after compiling the regular expression?
Did you try any external lib like Gson? Everything you need is just new Gson().fromJson(strResponse, new TypeToken<List<Card>>() {}.getType(););

Android Studio: How to get a Object with a List of Object with Spring-Resttemplate

I have to admit, that I need some help with something.
I have only 3 weeks experience with Rest, 2 weeks experience with Grails and one week experience with Android Studio, so I hope you won´t be too hard with me.
I get this Json from a grails Server:
{"class":"medicserver.Medication",
"id":1,"dateOfPrescription":"2015-09-19T08:12:34Z",
"description":"Meds",
"medicationUnit":[{"class":"medicserver.MedicationUnit","id":1},{"class":"medicserver.MedicationUnit","id":2},{"class":"medicserver.MedicationUnit","id":3}],
"patient":null}
You see, the attribute "medicationUnit" is a List of MedicationUnit and this is the only thing my ResponseObject doesn´t have, when it´s created. I simply don´t get it.
Here is Rest-Code:
RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter mapping = new MappingJackson2HttpMessageConverter();
mapping.setObjectMapper(new ObjectMapper());
restTemplate.getMessageConverters().add(mapping);
Medication medication = restTemplate.getForObject(url , Medication.class);
return medication;
My Classes - plaese ignore the static Type. This is to realise inner Classes :
#JsonIgnoreProperties(ignoreUnknown = true)
static class Medication{
String description;
MedicationUnit[] medicationUnit;
Date dateOfPrescription;
public Medication(){
}
public void setDescription(String description){
this.description = description;
}
public String getDescription(){
return this.description;
}
public void setMedicationUnit(MedicationUnit[] medicationUnit){
this.medicationUnit = medicationUnit;
}
public MedicationUnit[] getMedicationUnit(){
return this.medicationUnit;
}
public void setDateOfPrescription(Date dateOfPrescription){
this.dateOfPrescription = dateOfPrescription;
}
public Date getDateOfPrescription(){
return this.dateOfPrescription;
}
public String postAll(){
String result = this.description + "\n" + String.valueOf(this.dateOfPrescription) + "\n";
for(MedicationUnit med: this.medicationUnit){
result = result + med.postAll();
}
return result;
}
}
MedicationUnit:
#JsonIgnoreProperties(ignoreUnknown = true)
static class MedicationUnit {
String name="Hans";
Date intakeTime=new Date(0);
int dosage=3;
public MedicationUnit(){
}
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
public void setIntakeTime(Date intakeTime){
this.intakeTime=intakeTime;
}
public Date getIntakeTime(){
return this.intakeTime;
}
public void setDosage(int dosage){
this.dosage=dosage;
}
public int getDosage(){
return this.dosage;
}
private String postAll(){
String result;
result = this.name + " " + String.valueOf(this.intakeTime) + " " + String.valueOf(dosage) + "\n";
return result;
}
}

Categories

Resources