json to table structure api in Java - java

I have been searching in internet for a while to get a API that convert json into tabular format. I don't have any code which I tried. Please direct me if you have any idea about it.
Eg : Json
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656"},{"countryCode":91,"number":"675432"}],"OtherDetails":[{"Active":true}]}
Output can be(with any separated)
rinu|14|91|99862656|true
rinu|14|91|675432|true
I don't want any ready-made stuff, If I get anything similar to this, I can re-write it.

You might need this:
JacksonRead.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonRead {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
Example example = mapper.readValue(new File("d:\\user.json"),
Example.class);
StringBuilder builder = new StringBuilder();
int i = 0;
for (Phone phone : example.getPhone()) {
builder.append(example.getName()).append("|");
builder.append(example.getAge()).append("|");
builder.append(phone.getCountryCode()).append("|")
.append(phone.getNumber()).append("|")
.append(example.getOtherDetails().get(i).getActive())
.append("|");
builder.append("\n");
}
File file = new File("d:\\user.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(builder.toString());
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example.java
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
public class Example {
#JsonProperty("name")
private String name;
#JsonProperty("age")
private String age;
#JsonProperty("Phone")
private List<Phone> Phone = new ArrayList<Phone>();
#JsonProperty("OtherDetails")
private List<OtherDetail> OtherDetails = new ArrayList<OtherDetail>();
/**
*
* #return The name
*/
#JsonProperty("name")
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
/**
*
* #return The age
*/
#JsonProperty("age")
public String getAge() {
return age;
}
/**
*
* #param age
* The age
*/
#JsonProperty("age")
public void setAge(String age) {
this.age = age;
}
/**
*
* #return The Phone
*/
#JsonProperty("Phone")
public List<Phone> getPhone() {
return Phone;
}
/**
*
* #param Phone
* The Phone
*/
#JsonProperty("Phone")
public void setPhone(List<Phone> Phone) {
this.Phone = Phone;
}
/**
*
* #return The OtherDetails
*/
#JsonProperty("OtherDetails")
public List<OtherDetail> getOtherDetails() {
return OtherDetails;
}
/**
*
* #param OtherDetails
* The OtherDetails
*/
#JsonProperty("OtherDetails")
public void setOtherDetails(List<OtherDetail> OtherDetails) {
this.OtherDetails = OtherDetails;
}
#Override
public String toString() {
return "Example [name=" + name + ", age=" + age + ", Phone=" + Phone
+ ", OtherDetails=" + OtherDetails + "]";
}
}
Phone.java
import org.codehaus.jackson.annotate.JsonProperty;
public class Phone {
#JsonProperty("countryCode")
private Integer countryCode;
#JsonProperty("number")
private String number;
/**
*
* #return The countryCode
*/
#JsonProperty("countryCode")
public Integer getCountryCode() {
return countryCode;
}
/**
*
* #param countryCode
* The countryCode
*/
#JsonProperty("countryCode")
public void setCountryCode(Integer countryCode) {
this.countryCode = countryCode;
}
/**
*
* #return The number
*/
#JsonProperty("number")
public String getNumber() {
return number;
}
/**
*
* #param number
* The number
*/
#JsonProperty("number")
public void setNumber(String number) {
this.number = number;
}
#Override
public String toString() {
return "Phone [countryCode=" + countryCode + ", number=" + number + "]";
}
}
OtherDetail.java
import org.codehaus.jackson.annotate.JsonProperty;
public class OtherDetail {
#JsonProperty("Active")
private Boolean Active;
/**
*
* #return The Active
*/
#JsonProperty("Active")
public Boolean getActive() {
return Active;
}
/**
*
* #param Active
* The Active
*/
#JsonProperty("Active")
public void setActive(Boolean Active) {
this.Active = Active;
}
#Override
public String toString() {
return "OtherDetail [Active=" + Active + "]";
}
}
user.json
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656"},{"countryCode":91,"number":"675432"}],"OtherDetails":[{"Active":true}]}

I tried the library json2flat with the json
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656"},{"countryCode":91,"number":"675432"}],"OtherDetails":[{"Active":true}]}
it gives a CSV like ::
rinu|14|91|99862656|
rinu|14|91|675432 |
rinu| | | |true
But if you tweak the json a little bit like ::
{"name":"rinu","age":"14","Phone":[{"countryCode":91,"number":"99862656","Active":true},{"countryCode":91,"number":"675432","Active":true}]}
it gives the csv exactly as you require.
rinu|14|91|99862656|true
rinu|14|91|675432|true
Give it a try. After all the solution depends upon how the user wants to interpret the json.

Related

Return List within List REST API Jax Rs

I am creating a REST API from java where I am returning an object list as follows:
#Path("/order")
public class OrderService implements IService
{
#Override
public Response get()
{
List<DataObj> list = new ArrayList<>();
List<SubDataObj> subList = new ArrayList<>();
subList.add(new SubDataObj("1"));
GenericEntity<List<DataObj>> entity;
list.add(new DataObj("A", "22", TestEnum.test1, DateTime.now(), subList));
list.add(new DataObj("B", "23", TestEnum.test2, DateTime.now(), subList));
entity = new GenericEntity<List<DataObj>>(list){};
return Response.ok(entity).build();
}
}
Here the service returns the Response fine when not using the subList, which is a object list within the DataObj class. However, when I am using it, i get an error as:
SEVERE: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<dyno.scheduler.restservice.DataObj>.
Here are the DataObj and the SubDataObj classes:
#XmlRootElement
class DataObj
{
private String name;
private String age;
private TestEnum enumVal;
private DateTime currentDate;
private List<SubDataObj> subData;
public DataObj(String name, String age, TestEnum enumVal, DateTime currentDate, List<SubDataObj> subData)
{
this.name = name;
this.age = age;
this.enumVal = enumVal;
this.currentDate = currentDate;
this.subData = subData;
}
public DataObj() {}
/**
* #return the name
*/
public String getName()
{
return name;
}
/**
* #param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* #return the age
*/
public String getAge()
{
return age;
}
/**
* #param age the age to set
*/
public void setAge(String age)
{
this.age = age;
}
/**
* #return the enumVal
*/
public TestEnum getEnumVal()
{
return enumVal;
}
/**
* #param enumVal the enumVal to set
*/
public void setEnumVal(TestEnum enumVal)
{
this.enumVal = enumVal;
}
/**
* #return the currentDate
*/
public DateTime getCurrentDate()
{
return currentDate;
}
/**
* #param currentDate the currentDate to set
*/
public void setCurrentDate(DateTime currentDate)
{
this.currentDate = currentDate;
}
/**
* #return the subData
*/
public List<SubDataObj> getSubData()
{
return subData;
}
/**
* #param subData the subData to set
*/
public void setSubData(List<SubDataObj> subData)
{
this.subData = subData;
}
}
DataSubObj class:
class SubDataObj
{
private String subId;
public SubDataObj(String subId)
{
this.subId = subId;
}
/**
* #return the subId
*/
public String getSubId()
{
return subId;
}
/**
* #param subId the subId to set
*/
public void setSubId(String subId)
{
this.subId = subId;
}
}
I tried adding #XmlRootElement annotation to my SubDataObj class as well, which didn't work.
Any help would be appreciated!

Adding columns to grid using Vaadin 8.0.7

I want add column to grid, when i click to button ("backBtn"). Then i get the value from the textfield ("filterText"), and that will be the name of the new column. Who can help me? The code is from tutorial, but i need add the new feature here. Thanks ! You can find my code in attachment. Grid is in class "MyUI"
This is clas Customer
package my.vaadin.app;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Date;
/**
* A entity object, like in any other Java application. In a typical real world
* application this could for example be a JPA entity.
*/
#SuppressWarnings("serial")
public class Customer implements Serializable, Cloneable {
private Long id;
private String firstName = "";
private String datum = "";
private String lastName = "";
private LocalDate birthDate;
private CustomerStatus status;
private String email = "";
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* Get the value of email
*
* #return the value of email
*/
public String getEmail() {
return email;
}
/**
* Set the value of email
*
* #param email
* new value of email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Get the value of status
*
* #return the value of status
*/
public CustomerStatus getStatus() {
return status;
}
/**
* Set the value of status
*
* #param status
* new value of status
*/
public void setStatus(CustomerStatus status) {
this.status = status;
}
/**
* Get the value of birthDate
*
* #return the value of birthDate
*/
public LocalDate getBirthDate() {
return birthDate;
}
/**
* Set the value of birthDate
*
* #param birthDate
* new value of birthDate
*/
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
/**
* Get the value of lastName
*
* #return the value of lastName
*/
public String getLastName() {
return lastName;
}
/**
* Set the value of lastName
*
* #param lastName
* new value of lastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Get the value of firstName
*
* #return the value of firstName
*/
public String getFirstName() {
return firstName;
}
/**
* Set the value of firstName
*
* #param firstName
* new value of firstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getDatum() {
return datum;
}
/**
* Set the value of firstName
*
* #param firstName
* new value of firstName
*/
public void setDatum(String datum) {
this.datum = datum;
}
public boolean isPersisted() {
return id != null;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this.id == null) {
return false;
}
if (obj instanceof Customer && obj.getClass().equals(getClass())) {
return this.id.equals(((Customer) obj).id);
}
return false;
}
#Override
public int hashCode() {
int hash = 5;
hash = 43 * hash + (id == null ? 0 : id.hashCode());
return hash;
}
#Override
public Customer clone() throws CloneNotSupportedException {
return (Customer) super.clone();
}
#Override
public String toString() {
return firstName + " " + lastName;
}
}
This is clas MyUI
package my.vaadin.app;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.swing.text.TableView;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.Button;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.SelectionMode;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.components.grid.HeaderCell;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.themes.ValoTheme;
/**
* This UI is the application entry point. A UI may either represent a browser window
* (or tab) or some part of a html page where a Vaadin application is embedded.
* <p>
* The UI is initialized using {#link #init(VaadinRequest)}. This method is intended to be
* overridden to add component to the user interface and initialize non-component functionality.
*/
#Theme("mytheme")
public class MyUI extends UI {
private CustomerService service = CustomerService.getInstance();
private Grid<Customer> grid = new Grid<>(Customer.class);
private TextField filterText = new TextField();
// private CustomerForm form = new CustomerForm(this);
#Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
Label tancore = new Label();
filterText.setPlaceholder("Meno ...");
//filterText.addValueChangeListener(e -> updateList());
//filterText.setValueChangeMode(ValueChangeMode.LAZY);
Button clearFilterTextBtn = new Button(FontAwesome.TIMES);
clearFilterTextBtn.setDescription("Clear the current name");
clearFilterTextBtn.addClickListener(e -> filterText.clear());
tancore.setCaption("TanCore s.r.o");
CssLayout filtering = new CssLayout();
filtering.addComponents(filterText, clearFilterTextBtn);
filtering.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
Button addCustomerBtn = new Button("Pridaj zamestnanca");
Button downloadXlsBtn = new Button("Stiahnuť ako .xls");
Button loginBtn = new Button("Prihlásiť sa");
// Button addEmplBtn = new Button("Pridaj");
Button backBtn = new Button("Vlož");
downloadXlsBtn.setVisible(false);
TextField name = new TextField();
PasswordField pass = new PasswordField();
// addEmplBtn.setVisible(false);
addCustomerBtn.setVisible(false);
backBtn.setVisible(false);
filtering.setVisible(false);
clearFilterTextBtn.setVisible(false);
filterText.setVisible(false);
addCustomerBtn.setStyleName(ValoTheme.BUTTON_PRIMARY);
//.setStyleName(ValoTheme.BUTTON_PRIMARY);
addCustomerBtn.setClickShortcut(KeyCode.ENTER);
backBtn.addClickListener(e -> {
//Here i want include the new data after click on the button
//grid.addColumn(filterText.getValue()); -> That it's not good, because after click the Java will Warning you
addCustomerBtn.setVisible(true);
backBtn.setVisible(false);
filtering.setVisible(false);
clearFilterTextBtn.setVisible(false);
filterText.setVisible(false);
});
addCustomerBtn.addClickListener(e -> {
addCustomerBtn.setVisible(false);
filtering.setVisible(true);
backBtn.setVisible(true);
clearFilterTextBtn.setVisible(true);
filterText.setVisible(true);
//addEmplBtn.setEnabled(true);
});
loginBtn.addClickListener(e -> {
if(name.getValue().equals("admin"))
{
if(pass.getValue().equals("admin"))
{
name.setVisible(false);
pass.setVisible(false);
loginBtn.setVisible(false);
addCustomerBtn.setVisible(true);
downloadXlsBtn.setVisible(true);
}
}
});
pass.setPlaceholder("Heslo ...");
name.setPlaceholder("Meno ...");
HorizontalLayout toolbar = new HorizontalLayout(name, pass, loginBtn,filtering, addCustomerBtn,backBtn,downloadXlsBtn);
// grid.setSelectionMode(SelectionMode.MULTI);
grid.setColumns("datum", "lastName","email","status");
// grid.setStyleName(ValoTheme.BUTTON_PRIMARY);
/*HeaderRow extraHeader = grid.prependHeaderRow();
HeaderCell joinedCell = extraHeader.join("datum", "lastName");
joinedCell.setText("Joined cell");*/
HorizontalLayout main = new HorizontalLayout(grid);
main.setSizeFull();
grid.setSizeFull();
// main.setExpandRatio(grid, 1);
grid.getColumn("datum").setWidth(100);
// grid.getColumn("datum").set
// grid.getColumn("datum").set
grid.getColumn("datum").setCaption("Dátum");
grid.getColumn("lastName").setCaption("Adam");
layout.addComponents(toolbar, main);
// fetch list of Customers from service and assign it to Grid
updateList();
setContent(layout);
// form.setVisible(false);
grid.asSingleSelect().addValueChangeListener(event -> {
//if (event.getValue() == null) {
// form.setVisible(false);
//} else {
// form.setCustomer(event.getValue());
//}
});
}
public void updateList() {
List<Customer> customers = service.findAll(filterText.getValue());
grid.setItems(customers);
}
#WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
#VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
}
This is clas CustomerForm.java
package my.vaadin.app;
import com.vaadin.data.Binder;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.ui.Button;
import com.vaadin.ui.DateField;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.NativeSelect;
import com.vaadin.ui.TextField;
import com.vaadin.ui.themes.ValoTheme;
public class CustomerForm extends FormLayout {
private TextField firstName = new TextField("First name");
private TextField lastName = new TextField("Last name");
private TextField email = new TextField("Email");
private NativeSelect<CustomerStatus> status = new NativeSelect<>("Status");
private DateField birthdate = new DateField("Birthday");
private Button save = new Button("Save");
private Button delete = new Button("Delete");
private CustomerService service = CustomerService.getInstance();
private Customer customer;
private MyUI myUI;
private Binder<Customer> binder = new Binder<>(Customer.class);
public CustomerForm(MyUI myUI) {
this.myUI = myUI;
setSizeUndefined();
HorizontalLayout buttons = new HorizontalLayout(save, delete);
addComponents(firstName, lastName, email, status, birthdate, buttons);
status.setItems(CustomerStatus.values());
save.setStyleName(ValoTheme.BUTTON_PRIMARY);
save.setClickShortcut(KeyCode.ENTER);
binder.bindInstanceFields(this);
save.addClickListener(e -> this.save());
delete.addClickListener(e -> this.delete());
}
public void setCustomer(Customer customer) {
this.customer = customer;
binder.setBean(customer);
// Show delete button for only customers already in the database
delete.setVisible(customer.isPersisted());
setVisible(true);
firstName.selectAll();
}
private void delete() {
service.delete(customer);
myUI.updateList();
setVisible(false);
}
private void save() {
service.save(customer);
myUI.updateList();
setVisible(false);
}
}
This is clas CustomerService.java
package my.vaadin.app;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* An in memory dummy "database" for the example purposes. In a typical Java app
* this class would be replaced by e.g. EJB or a Spring based service class.
* <p>
* In demos/tutorials/examples, get a reference to this service class with
* {#link CustomerService#getInstance()}.
*/
public class CustomerService {
private static CustomerService instance;
private static final Logger LOGGER = Logger.getLogger(CustomerService.class.getName());
private final HashMap<Long, Customer> contacts = new HashMap<>();
private long nextId = 0;
private CustomerService() {
}
/**
* #return a reference to an example facade for Customer objects.
*/
public static CustomerService getInstance() {
if (instance == null) {
instance = new CustomerService();
instance.ensureTestData();
}
return instance;
}
/**
* #return all available Customer objects.
*/
public synchronized List<Customer> findAll() {
return findAll(null);
}
/**
* Finds all Customer's that match given filter.
*
* #param stringFilter
* filter that returned objects should match or null/empty string
* if all objects should be returned.
* #return list a Customer objects
*/
public synchronized List<Customer> findAll(String stringFilter) {
ArrayList<Customer> arrayList = new ArrayList<>();
for (Customer contact : contacts.values()) {
try {
boolean passesFilter = (stringFilter == null || stringFilter.isEmpty())
|| contact.toString().toLowerCase().contains(stringFilter.toLowerCase());
if (passesFilter) {
arrayList.add(contact.clone());
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(CustomerService.class.getName()).log(Level.SEVERE, null, ex);
}
}
Collections.sort(arrayList, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return (int) (o2.getId() - o1.getId());
}
});
return arrayList;
}
/**
* Finds all Customer's that match given filter and limits the resultset.
*
* #param stringFilter
* filter that returned objects should match or null/empty string
* if all objects should be returned.
* #param start
* the index of first result
* #param maxresults
* maximum result count
* #return list a Customer objects
*/
public synchronized List<Customer> findAll(String stringFilter, int start, int maxresults) {
ArrayList<Customer> arrayList = new ArrayList<>();
for (Customer contact : contacts.values()) {
try {
boolean passesFilter = (stringFilter == null || stringFilter.isEmpty())
|| contact.toString().toLowerCase().contains(stringFilter.toLowerCase());
if (passesFilter) {
arrayList.add(contact.clone());
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(CustomerService.class.getName()).log(Level.SEVERE, null, ex);
}
}
Collections.sort(arrayList, new Comparator<Customer>() {
#Override
public int compare(Customer o1, Customer o2) {
return (int) (o2.getId() - o1.getId());
}
});
int end = start + maxresults;
if (end > arrayList.size()) {
end = arrayList.size();
}
return arrayList.subList(start, end);
}
/**
* #return the amount of all customers in the system
*/
public synchronized long count() {
return contacts.size();
}
/**
* Deletes a customer from a system
*
* #param value
* the Customer to be deleted
*/
public synchronized void delete(Customer value) {
contacts.remove(value.getId());
}
/**
* Persists or updates customer in the system. Also assigns an identifier
* for new Customer instances.
*
* #param entry
*/
public synchronized void save(Customer entry) {
if (entry == null) {
LOGGER.log(Level.SEVERE,
"Customer is null. Are you sure you have connected your form to the application as described in tutorial chapter 7?");
return;
}
if (entry.getId() == null) {
entry.setId(nextId++);
}
try {
entry = (Customer) entry.clone();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
contacts.put(entry.getId(), entry);
}
/**
* Sample data generation
*/
public void ensureTestData() {
if (findAll().isEmpty()) {
for (int i = 31; i > 0; i--) {
Customer c = new Customer();
c.setDatum(i+".7");
save(c);
}
}
}
}
I want have this in my WebApp
This is actualy my WebApp

Deserialize Array Of Objects with the first item being the counter of the elements

Hello i was trying to deserialize the following JSON response from a Web Api:
{
"response": [
370968,
{
"aid": 65843156,
"owner_id": 17519165,
"artist": "Bass Test",
"title": "дурной басс!",
"duration": 238,
"url": "http://cs6-10v4.vk-cdn.net/p22/c412a04df93035.mp3?extra=9YguhLftfZDDwo4JKBVwvlx_V1vwlu5pNU4-WremEqM9bL8eN2vh3_qu7bAg9EgNCj0ztEcMurarC499x8X2MpUaipykG2LDueWe0QQMrIPplkxKdV1xcQp35baDwA84l-luVxai9maX",
"lyrics_id": "6214304"
},
{
"aid": 207425918,
"owner_id": 96085484,
"artist": "► DJ Pleased",
"title": "Bass Test № 04 (New 2013)",
"duration": 328,
"url": "http://cs6-7v4.vk-cdn.net/p23/6d7071221fb912.mp3?extra=O5ih5W5YkaEkXhHQSOKeDzvtr0V8xyS1WhIgjYLROFOMcW__FpU3mSf5udwdEAq6kkcz7QSy5jB57rTgSxnRJXCySZy2b0J_a2DvzFUBqVX6lcKqlarTryP_loQyk-SYPbFLh-9mSzm_iA",
"lyrics_id": "86651563",
"genre": 10
}
]
}
My intention is to build a class to get the items in the response and use them in my Java Android application. The problem is that the first item of the response array is a number and not an object like the next items. So when I parse it with Gson it gives me the error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 20 path $.response[0]
I used the retrofit android library with the following POJO class (witch works if i don't have the counter in the response):
import java.util.HashMap;
import java.util.Map;
public class Response {
private Integer aid;
private Integer ownerId;
private String artist;
private String title;
private Integer duration;
private String url;
private String lyricsId;
private Integer genre;
private String album;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The aid
*/
public Integer getAid() {
return aid;
}
/**
*
* #param aid
* The aid
*/
public void setAid(Integer aid) {
this.aid = aid;
}
/**
*
* #return
* The ownerId
*/
public Integer getOwnerId() {
return ownerId;
}
/**
*
* #param ownerId
* The owner_id
*/
public void setOwnerId(Integer ownerId) {
this.ownerId = ownerId;
}
/**
*
* #return
* The artist
*/
public String getArtist() {
return artist;
}
/**
*
* #param artist
* The artist
*/
public void setArtist(String artist) {
this.artist = artist;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The duration
*/
public Integer getDuration() {
return duration;
}
/**
*
* #param duration
* The duration
*/
public void setDuration(Integer duration) {
this.duration = duration;
}
/**
*
* #return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* #param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* #return
* The lyricsId
*/
public String getLyricsId() {
return lyricsId;
}
/**
*
* #param lyricsId
* The lyrics_id
*/
public void setLyricsId(String lyricsId) {
this.lyricsId = lyricsId;
}
/**
*
* #return
* The genre
*/
public Integer getGenre() {
return genre;
}
/**
*
* #param genre
* The genre
*/
public void setGenre(Integer genre) {
this.genre = genre;
}
/**
*
* #return
* The album
*/
public String getAlbum() {
return album;
}
/**
*
* #param album
* The album
*/
public void setAlbum(String album) {
this.album = album;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
Is there any way to make it work? I don't have access to the API server so i cant change how the result is displayed. To generate the class i used http://www.jsonschema2pojo.org/ but i was able to generate it only by removing the counter from the response.
The wrapper class VKSongApi:
public class VKSongApi {
private List<Response> response = new ArrayList<Response>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The response
*/
public List<Response> getResponse() {
return response;
}
/**
*
* #param response
* The response
*/
public void setResponse(List<Response> response) {
this.response = response;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
The retrofit interface class is:
public interface VKApi {
#GET("/method/audio.search")
Call<VKSongApi> search(#Query("q") String query, #Query("access_token") String token);
}
Then in the MainActivity i do:
public static final String BASE_URL = "https://api.vk.com/method/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
VKApi apiService =
retrofit.create(VKApi.class);
And call the method from the MainActivity with:
Call<VKSongApi> call = apiService.search("test","fff9ef502df4bb10d9bf50dcd62170a24c69e98e4d847d9798d63dacf474b674f9a512b2b3f7e8ebf1d69");
call.enqueue(new Callback<VKSongApi>() {
#Override
public void onResponse(Call<VKSongApi> call, Response<VKSongApi> response) {
int statusCode = response.code();
VKSongApi song = response.body();
Log.d(TAG,response.message());
}
#Override
public void onFailure(Call<VKSongApi> call, Throwable t) {
//Here the error occurs com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 20 path $.response[0]
Log.d(TAG,"Failure");
}
});
I solved by parsing manually the response using a custom deserializer class

database insert from a model, no such column exception,

firstly i have trouble with creating database,then i want to put my received huge json datas(i converted json to java model by GsonBuilder and i saw all the datas in my entity[] list which made from ReceivedEntityModel class) to database,but i failed at first steps.it never creates my columns,so that after insertion there is 0 rowcount:(, i read all those answers about this topic and they didn't help me at all.I'm stuck.Anyone can help??
public void onCreate(SQLiteDatabase db)
{
String CREATE_M_ENTITY_TABLE = "CREATE TABLE " + TABLE_2_NAME + " ("
+ rId + " INTEGER PRIMARY KEY, "
+ ParentId + " INTEGER, "
+ Code+ " INTEGER, "
+ Label + " TEXT, "
+ LabelFL + " TEXT, "
+ EntityGroupId + " INTEGER, "
+ Property + " TEXT, "
+ ReportCode+ " INTEGER, "
+ Description + " TEXT, "
+ Code1Id + " INTEGER, "
+ Code2Id + " INTEGER, "
+ Code3Id + " INTEGER, "
+ Code4Id+ " INTEGER, "
+ Code5Id + " INTEGER, "
+ DefaultDimension1+ " INTEGER, "
+ DefaultDimension2 + "INTEGER, "
+ DefaultDimension3 + " INTEGER, "
+ CompanyId + " INTEGER, "
+ BranchId + " INTEGER, "
+ ReferenceDate + " TEXT, "
+ ResField1+ " TEXT, "
+ ResField2 + " TEXT, "
+ AreaId + " INTEGER, "
+ ModifiedDateTime + " TEXT, "
+ CreatedDateTime + " TEXT, "
+ RecId + " INTEGER, "
+ IsActive + " BIT,"
+ ModifiedBy + " INTEGER,"
+ CreatedBy + " INTEGER" + ") ";
db.execSQL(CREATE_M_ENTITY_TABLE);
}
i call this function at main activity to bind listview
public Cursor fetchEntities()
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
String myQuery="Select Code, Label from entity";
Cursor mCursor=db.rawQuery(myQuery,null);
int rowCount=mCursor.getCount();
//Cursor mCursor = db.query(TABLE_2_NAME, new String[] {Code, Label }, null,null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//as you see there is paramater like ReceivedEntityModel ,i get the datas from this Model's getters and i want to put them into a database is shown below.
public void AddNewEntity(ReceivedEntityModel[] entity)
{
// addnewentity
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
for (int i = 0; i < entity.length; i++) {
values.put(rId, entity[i].getRId());
values.put(ParentId, entity[i].getParentId());
values.put(Code, entity[i].getCode());
values.put(Label, entity[i].getLabel());
values.put(LabelFL, entity[i].getLabelFL());
values.put(EntityGroupId, entity[i].getEntityGroupId());
values.put(ReportCode, entity[i].getReportCode());
values.put(Description, entity[i].getDescription());
values.put(Code1Id, entity[i].getCode1Id());
values.put(Code2Id, entity[i].getCode2Id());
values.put(Code3Id, entity[i].getCode3Id());
values.put(Code4Id, entity[i].getCode4Id());
values.put(Code5Id, entity[i].getCode5Id());
values.put(DefaultDimension1, entity[i].getDefaultDimension1Id());
values.put(DefaultDimension2, entity[i].getDefaultDimension2Id());
values.put(DefaultDimension3, entity[i].getDefaultDimension3Id());
values.put(CompanyId, entity[i].getCompanyId());
values.put(BranchId, entity[i].getBranchId());
values.put(ReferenceDate, entity[i].getReferenceDate());
values.put(ResField1, (String) entity[i].getResField1());
values.put(ResField2, (String) entity[i].getResField2());
values.put(AreaId, entity[i].getAreaId());
values.put(ModifiedDateTime, entity[i].getModifiedDateTime());
values.put(CreatedDateTime, entity[i].getCreatedDateTime());
values.put(RecId, entity[i].getRecId());
values.put(IsActive, entity[i].getIsActive());
values.put(ModifiedBy, entity[i].getModifiedBy());
values.put(CreatedBy, (String) entity[i].getCreatedBy());
}
db.insert(TABLE_2_NAME, null, values);
db.close();
}
this is Setup.java,fetchEntities(),AddNewEntity() functions are calling from there.Gson Builder make me a model.And the i call AddNewEntity()
protected String doInBackground(String... urls) {
entityReqestInfo = new EntityReqestInfo();
String cevap = POST_FOR_ENTITY(urls[0], entityReqestInfo);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
receivedEM = gson.fromJson(cevap, ReceivedEntityModel[].class);
myDB.getDatabaseEntityOperations().AddNewEntity(receivedEM);
pDialog.cancel();
return cevap;
}
and last of all my generated entity Model ReceivedEntityModel class
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReceivedEntityModel {
private Integer rId;
private Integer ParentId;
private String Code;
private String Label;
private String LabelFL;
private Integer EntityGroupId;
private String Property;
private String ReportCode;
private String Description;
private Integer Code1Id;
private Integer Code2Id;
private Integer Code3Id;
private Integer Code4Id;
private Integer Code5Id;
private Integer DefaultDimension1Id;
private Integer DefaultDimension2Id;
private Integer DefaultDimension3Id;
private Integer CompanyId;
private Integer BranchId;
private String ReferenceDate;
private String ResField1;
private String ResField2;
private String AreaId;
private String ModifiedDateTime;
private String CreatedDateTime;
private Integer RecId;
private Boolean IsActive;
private Integer ModifiedBy;
private String CreatedBy;
private String DBranch;
private String DCompany;
private String MEntityGroup;
private List<String> MEntityTableModule = new ArrayList<String>();
private Map<String, String> additionalProperties = new HashMap<String, String>();
/**
*
* #return The rId
*/
public Integer getRId() {
return rId;
}
/**
*
* #param rId
* The rId
*/
public void setRId(Integer rId) {
this.rId = rId;
}
public ReceivedEntityModel withRId(Integer rId) {
this.rId = rId;
return this;
}
/**
*
* #return The ParentId
*/
public Integer getParentId() {
return ParentId;
}
/**
*
* #param ParentId
* The ParentId
*/
public void setParentId(Integer ParentId) {
this.ParentId = ParentId;
}
public ReceivedEntityModel withParentId(Integer ParentId) {
this.ParentId = ParentId;
return this;
}
/**
*
* #return The Code
*/
public String getCode() {
return Code;
}
/**
*
* #param Code
* The Code
*/
public void setCode(String Code) {
this.Code = Code;
}
public ReceivedEntityModel withCode(String Code) {
this.Code = Code;
return this;
}
/**
*
* #return The Label
*/
public String getLabel() {
return Label;
}
/**
*
* #param Label
* The Label
*/
public void setLabel(String Label) {
this.Label = Label;
}
public ReceivedEntityModel withLabel(String Label) {
this.Label = Label;
return this;
}
/**
*
* #return The LabelFL
*/
public String getLabelFL() {
return LabelFL;
}
/**
*
* #param LabelFL
* The LabelFL
*/
public void setLabelFL(String LabelFL) {
this.LabelFL = LabelFL;
}
public ReceivedEntityModel withLabelFL(String LabelFL) {
this.LabelFL = LabelFL;
return this;
}
/**
*
* #return The EntityGroupId
*/
public Integer getEntityGroupId() {
return EntityGroupId;
}
/**
*
* #param EntityGroupId
* The EntityGroupId
*/
public void setEntityGroupId(Integer EntityGroupId) {
this.EntityGroupId = EntityGroupId;
}
public ReceivedEntityModel withEntityGroupId(Integer EntityGroupId) {
this.EntityGroupId = EntityGroupId;
return this;
}
/**
*
* #return The Property
*/
public String getProperty() {
return Property;
}
/**
*
* #param Property
* The Property
*/
public void setProperty(String Property) {
this.Property = Property;
}
public ReceivedEntityModel withProperty(String Property) {
this.Property = Property;
return this;
}
/**
*
* #return The ReportCode
*/
public String getReportCode() {
return ReportCode;
}
/**
*
* #param ReportCode
* The ReportCode
*/
public void setReportCode(String ReportCode) {
this.ReportCode = ReportCode;
}
public ReceivedEntityModel withReportCode(String ReportCode) {
this.ReportCode = ReportCode;
return this;
}
/**
*
* #return The Description
*/
public String getDescription() {
return Description;
}
/**
*
* #param Description
* The Description
*/
public void setDescription(String Description) {
this.Description = Description;
}
public ReceivedEntityModel withDescription(String Description) {
this.Description = Description;
return this;
}
/**
*
* #return The Code1Id
*/
public Integer getCode1Id() {
return Code1Id;
}
/**
*
* #param Code1Id
* The Code1Id
*/
public void setCode1Id(Integer Code1Id) {
this.Code1Id = Code1Id;
}
public ReceivedEntityModel withCode1Id(Integer Code1Id) {
this.Code1Id = Code1Id;
return this;
}
/**
*
* #return The Code2Id
*/
public Integer getCode2Id() {
return Code2Id;
}
/**
*
* #param Code2Id
* The Code2Id
*/
public void setCode2Id(Integer Code2Id) {
this.Code2Id = Code2Id;
}
public ReceivedEntityModel withCode2Id(Integer Code2Id) {
this.Code2Id = Code2Id;
return this;
}
/**
*
* #return The Code3Id
*/
public Integer getCode3Id() {
return Code3Id;
}
/**
*
* #param Code3Id
* The Code3Id
*/
public void setCode3Id(Integer Code3Id) {
this.Code3Id = Code3Id;
}
public ReceivedEntityModel withCode3Id(Integer Code3Id) {
this.Code3Id = Code3Id;
return this;
}
/**
*
* #return The Code4Id
*/
public Integer getCode4Id() {
return Code4Id;
}
/**
*
* #param Code4Id
* The Code4Id
*/
public void setCode4Id(Integer Code4Id) {
this.Code4Id = Code4Id;
}
public ReceivedEntityModel withCode4Id(Integer Code4Id) {
this.Code4Id = Code4Id;
return this;
}
/**
*
* #return The Code5Id
*/
public Integer getCode5Id() {
return Code5Id;
}
/**
*
* #param Code5Id
* The Code5Id
*/
public void setCode5Id(Integer Code5Id) {
this.Code5Id = Code5Id;
}
public ReceivedEntityModel withCode5Id(Integer Code5Id) {
this.Code5Id = Code5Id;
return this;
}
/**
*
* #return The DefaultDimension1Id
*/
public Integer getDefaultDimension1Id() {
return DefaultDimension1Id;
}
/**
*
* #param DefaultDimension1Id
* The DefaultDimension1Id
*/
public void setDefaultDimension1Id(Integer DefaultDimension1Id) {
this.DefaultDimension1Id = DefaultDimension1Id;
}
public ReceivedEntityModel withDefaultDimension1Id(
Integer DefaultDimension1Id) {
this.DefaultDimension1Id = DefaultDimension1Id;
return this;
}
/**
*
* #return The DefaultDimension2Id
*/
public Integer getDefaultDimension2Id() {
return DefaultDimension2Id;
}
/**
*
* #param DefaultDimension2Id
* The DefaultDimension2Id
*/
public void setDefaultDimension2Id(Integer DefaultDimension2Id) {
this.DefaultDimension2Id = DefaultDimension2Id;
}
public ReceivedEntityModel withDefaultDimension2Id(
Integer DefaultDimension2Id) {
this.DefaultDimension2Id = DefaultDimension2Id;
return this;
}
/**
*
* #return The DefaultDimension3Id
*/
public Integer getDefaultDimension3Id() {
return DefaultDimension3Id;
}
/**
*
* #param DefaultDimension3Id
* The DefaultDimension3Id
*/
public void setDefaultDimension3Id(Integer DefaultDimension3Id) {
this.DefaultDimension3Id = DefaultDimension3Id;
}
public ReceivedEntityModel withDefaultDimension3Id(
Integer DefaultDimension3Id) {
this.DefaultDimension3Id = DefaultDimension3Id;
return this;
}
/**
*
* #return The CompanyId
*/
public Integer getCompanyId() {
return CompanyId;
}
/**
*
* #param CompanyId
* The CompanyId
*/
public void setCompanyId(Integer CompanyId) {
this.CompanyId = CompanyId;
}
public ReceivedEntityModel withCompanyId(Integer CompanyId) {
this.CompanyId = CompanyId;
return this;
}
/**
*
* #return The BranchId
*/
public Integer getBranchId() {
return BranchId;
}
/**
*
* #param BranchId
* The BranchId
*/
public void setBranchId(Integer BranchId) {
this.BranchId = BranchId;
}
public ReceivedEntityModel withBranchId(Integer BranchId) {
this.BranchId = BranchId;
return this;
}
/**
*
* #return The ReferenceDate
*/
public String getReferenceDate() {
return ReferenceDate;
}
/**
*
* #param ReferenceDate
* The ReferenceDate
*/
public void setReferenceDate(String ReferenceDate) {
this.ReferenceDate = ReferenceDate;
}
public ReceivedEntityModel withReferenceDate(String ReferenceDate) {
this.ReferenceDate = ReferenceDate;
return this;
}
/**
*
* #return The ResField1
*/
public String getResField1() {
return ResField1;
}
/**
*
* #param ResField1
* The ResField1
*/
public void setResField1(String ResField1) {
this.ResField1 = ResField1;
}
public ReceivedEntityModel withResField1(String ResField1) {
this.ResField1 = ResField1;
return this;
}
/**
*
* #return The ResField2
*/
public String getResField2() {
return ResField2;
}
/**
*
* #param ResField2
* The ResField2
*/
public void setResField2(String ResField2) {
this.ResField2 = ResField2;
}
public ReceivedEntityModel withResField2(String ResField2) {
this.ResField2 = ResField2;
return this;
}
/**
*
* #return The AreaId
*/
public String getAreaId() {
return AreaId;
}
/**
*
* #param AreaId
* The AreaId
*/
public void setAreaId(String AreaId) {
this.AreaId = AreaId;
}
public ReceivedEntityModel withAreaId(String AreaId) {
this.AreaId = AreaId;
return this;
}
/**
*
* #return The ModifiedDateTime
*/
public String getModifiedDateTime() {
return ModifiedDateTime;
}
/**
*
* #param ModifiedDateTime
* The ModifiedDateTime
*/
public void setModifiedDateTime(String ModifiedDateTime) {
this.ModifiedDateTime = ModifiedDateTime;
}
public ReceivedEntityModel withModifiedDateTime(String ModifiedDateTime) {
this.ModifiedDateTime = ModifiedDateTime;
return this;
}
/**
*
* #return The CreatedDateTime
*/
public String getCreatedDateTime() {
return CreatedDateTime;
}
/**
*
* #param CreatedDateTime
* The CreatedDateTime
*/
public void setCreatedDateTime(String CreatedDateTime) {
this.CreatedDateTime = CreatedDateTime;
}
public ReceivedEntityModel withCreatedDateTime(String CreatedDateTime) {
this.CreatedDateTime = CreatedDateTime;
return this;
}
/**
*
* #return The RecId
*/
public Integer getRecId() {
return RecId;
}
/**
*
* #param RecId
* The RecId
*/
public void setRecId(Integer RecId) {
this.RecId = RecId;
}
public ReceivedEntityModel withRecId(Integer RecId) {
this.RecId = RecId;
return this;
}
/**
*
* #return The IsActive
*/
public Boolean getIsActive() {
return IsActive;
}
/**
*
* #param IsActive
* The IsActive
*/
public void setIsActive(Boolean IsActive) {
this.IsActive = IsActive;
}
public ReceivedEntityModel withIsActive(Boolean IsActive) {
this.IsActive = IsActive;
return this;
}
/**
*
* #return The ModifiedBy
*/
public Integer getModifiedBy() {
return ModifiedBy;
}
/**
*
* #param ModifiedBy
* The ModifiedBy
*/
public void setModifiedBy(Integer ModifiedBy) {
this.ModifiedBy = ModifiedBy;
}
public ReceivedEntityModel withModifiedBy(Integer ModifiedBy) {
this.ModifiedBy = ModifiedBy;
return this;
}
/**
*
* #return The CreatedBy
*/
public String getCreatedBy() {
return CreatedBy;
}
/**
*
* #param CreatedBy
* The CreatedBy
*/
public void setCreatedBy(String CreatedBy) {
this.CreatedBy = CreatedBy;
}
public ReceivedEntityModel withCreatedBy(String CreatedBy) {
this.CreatedBy = CreatedBy;
return this;
}
/**
*
* #return The DBranch
*/
public String getDBranch() {
return DBranch;
}
/**
*
* #param DBranch
* The D_Branch
*/
public void setDBranch(String DBranch) {
this.DBranch = DBranch;
}
public ReceivedEntityModel withDBranch(String DBranch) {
this.DBranch = DBranch;
return this;
}
/**
*
* #return The DCompany
*/
public String getDCompany() {
return DCompany;
}
/**
*
* #param DCompany
* The D_Company
*/
public void setDCompany(String DCompany) {
this.DCompany = DCompany;
}
public ReceivedEntityModel withDCompany(String DCompany) {
this.DCompany = DCompany;
return this;
}
/**
*
* #return The MEntityGroup
*/
public String getMEntityGroup() {
return MEntityGroup;
}
/**
*
* #param MEntityGroup
* The M_EntityGroup
*/
public void setMEntityGroup(String MEntityGroup) {
this.MEntityGroup = MEntityGroup;
}
public ReceivedEntityModel withMEntityGroup(String MEntityGroup) {
this.MEntityGroup = MEntityGroup;
return this;
}
/**
*
* #return The MEntityTableModule
*/
public List<String> getMEntityTableModule() {
return MEntityTableModule;
}
/**
*
* #param MEntityTableModule
* The M_EntityTableModule
*/
public void setMEntityTableModule(List<String> MEntityTableModule) {
this.MEntityTableModule = MEntityTableModule;
}
public ReceivedEntityModel withMEntityTableModule(
List<String> MEntityTableModule) {
this.MEntityTableModule = MEntityTableModule;
return this;
}
public Map<String, String> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, String value) {
this.additionalProperties.put(name, value);
}
public ReceivedEntityModel withAdditionalProperty(String name, String value) {
this.additionalProperties.put(name, value);
return this;
}
}
Where are the column names defined?
The DefaultDimension2 column is not created with the intended name
in your table, because you forgot a space here:
+ DefaultDimension2 + "INTEGER, "
It must be
+ DefaultDimension2 + " INTEGER, "
So, supposing that the DefaultDimension2 column name is defined as
public String DefaultDimension2 = "DefaultDimension2";
it is actually created as "DefaultDimension2INTEGER, " instead of "DefaultDimension2 INTEGER, "
It's really a common mistake, mostly due to hurry.

How to fix Out of START_ARRAY token Error

Can anybody say where I am doing wrong. I have json like that
[{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"},{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"},{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"},{"name":"foo","slug":"foo2","locales":["foo3"],"hostname":"foo4","region_tag":"foo5"}]
And I parse to this class.
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
#JsonPropertyOrder({
"shards"
})
public class ShardsResponse extends Response{
#JsonProperty("shards")
private List<Shards> shards = new ArrayList<Shards>();
/**
*
* #return
* The shards
*/
#JsonProperty("shards")
public List<Shards> getShards() {
return shards;
}
/**
*
* #param shards
* The shards
*/
#JsonProperty("shards")
public void setShards(List<Shards> shards) {
this.shards = shards;
}
}
And Shards class is :
/**
*
* #return
* The locales
*/
#JsonProperty("locales")
public List<String> getLocales() {
return locales;
}
/**
*
* #param locales
* The locales
*/
#JsonProperty("locales")
public void setLocales(List<String> locales) {
this.locales = locales;
}
/**
*
* #return
* The name
*/
#JsonProperty("name")
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The hostname
*/
#JsonProperty("hostname")
public String getHostname() {
return hostname;
}
/**
*
* #param hostname
* The hostname
*/
#JsonProperty("hostname")
public void setHostname(String hostname) {
this.hostname = hostname;
}
/**
*
* #return
* The slug
*/
#JsonProperty("slug")
public String getSlug() {
return slug;
}
/**
*
* #param slug
* The slug
*/
#JsonProperty("slug")
public void setSlug(String slug) {
this.slug = slug;
}
}
So I'm using ObjectMapper.readValue(jsontext, responseclass)
JSONObject object = new JSONObject(JsonString);
JsonString = "";
Iterator<String> keys= object.keys();
while (keys.hasNext()){
String keyValue = (String)keys.next();
JsonString= JsonString+ object.getString(keyValue);
}
JsonString= JsonString.substring(1, JsonString.length()-1);
Object response = ObjectMapper.readValue(JsonString, ShardsResponse.class);
At the last I am getting out of START_ARRAY token. Please anybody tell me what's wrong.
Cause I'm trying so much things, but I never find the solution.
How can I fix it.
Your json string is correct, but not for the object you expect, as someone mentioned already, you need to use a List
import java.io.IOException;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
public class ParseJson {
private static final String jsonString = "[{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"},{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"},{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"},{\"name\":\"foo\",\"slug\":\"foo2\",\"locales\":[\"foo3\"],\"hostname\":\"foo4\",\"region_tag\":\"foo5\"}]";
public static void parse() {
try {
TypeReference<List<Shards>> typeRef = new TypeReference<List<Shards>>() { };
ObjectMapper mapper = new ObjectMapper();
List<Shards> list = mapper.readValue(jsonString, typeRef);
for ( Shards s : list )
{
s.printDebug();
}
ShardsResponse sr = new ShardsResponse(list);
String srString = mapper.writeValueAsString(sr);
System.out.println("srString: " + srString );
TypeReference<ShardsResponse> typeRef2 = new TypeReference<ShardsResponse>() { };
ShardsResponse sr2 = mapper.readValue(srString, typeRef2);
sr2.printDebug();
} catch ( IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ParseJson.parse();
}
}
Edit:
If you expect a ShardsResponse back, your json string should look like this:
{"shards":[{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"},{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"},{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"},{"locales":["foo3"],"name":"foo","hostname":"foo4","slug":"foo2","region_tag":"foo5"}]}
Easiest way to figure out what the json will look like is to dump it out:
ShardsResponse sr = new ShardsResponse(list);
String srString = mapper.writeValueAsString(sr);
System.out.println("srString: " + srString );
Edit:
Adding additional Classes for clarity:
ShardsResponses.java
import java.util.ArrayList;
import java.util.List;
public class ShardsResponse {
private List<Shards> shards = new ArrayList<Shards>();
public ShardsResponse() { }
public ShardsResponse( List<Shards> shards)
{
this.shards = shards;
}
public List<Shards> getShards() {
return shards;
}
public void setShards(List<Shards> shards) {
this.shards = shards;
}
public void printDebug()
{
for ( Shards s : shards)
{
s.printDebug();
System.out.println("");
}
}
}
Shards.java:
import java.util.List;
public class Shards {
private List<String> locales;
private String name;
private String hostname;
private String slug;
private String region_tag;
public List<String> getLocales() {
return locales;
}
public void setLocales(List<String> locales) {
this.locales = locales;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public void printDebug()
{
System.out.println("name: " + name);
System.out.println("hostname: " + hostname);
System.out.println("slug: " + slug);
System.out.println("region_tag: " + region_tag);
for ( String s : locales )
{
System.out.println("Locals: " + locales);
}
}
public String getRegion_tag() {
return region_tag;
}
public void setRegion_tag(String region_tag) {
this.region_tag = region_tag;
}
}
you have an jsonArray but you are trying to parse a jsonObject. change your method to return a list of objects instead of one object.

Categories

Resources