I need deserialize a string(json) to a arraylist inside a model. I'm using the Jackson-Annotation library to do this. Anyone can help me?
I've tried this, but doesn't work:
#JsonDeserialize(as = Model.class)
private ArrayList<Model> model;
or:
#JsonDeserialize(as = ArrayModel.class) //ArrayModel extends arrayList<Model>
private ArrayList<Model> model;
Sample:
public class Model extends BaseModel {
#JsonProperty("id")
private int id;
#JsonDeserialize(as = ModelTwo.class)
private ArrayList<ModelTwo> modelTwo;
public ArrayList<ModelTwo> getModelTwo() {
return modelTwo;
}
public void setModelTwo(ArrayList<ModelTwo> modelTwo) {
this.modelTwo = modelTwo;
}
}
I've solved this!
You need say the type of Object and the type of content.
After this, you need create a new Json with properties on params.
On first model:
#JsonProperty("property")
#JsonDeserialize(as=ArrayList.class, contentAs=ModelTwo.class)
private List<ModelTwo> modelsTwo;
On second model:
#JsonCreator
public ModelTwo(
#JsonProperty("id") int id,
#JsonProperty("name") String name) {
this.id = id;
this.name = name;
}
Related
I have the following class that I want to store in firestore.
public class User extends Model {
#PropertyName("user_auth_id")
public String authUid;
#PropertyName("first_name")
public String firstName;
#PropertyName("last_name")
public String lastName;
#PropertyName("picture_url")
public String pictureUrl;
#PropertyName("email")
public String email;
#PropertyName("companies")
public ArrayList<UserCompany> companies;
public User() {}
}
public class UserCompany extends Model {
public String name;
public String role;
public String position;
public UserCompany() {
super();
}
public UserCompany(Company company, String role, String position) {
this();
name = company.name;
this.role = role;
this.position = position;
}
public Map<String, Object> toObject() {
Map<String, Object> object = new HashMap<>();
object.put("id", id);
object.put("name", name);
object.put("role", role);
object.put("position", position);
return object;
}
}
#IgnoreExtraProperties
public class Model {
#Exclude
public String id;
public <T extends Model> T withId(#NonNull final String id) {
this.id = id;
return (T) this;
}
}
And I want to use a transaction to update an user entry with it's newly created company list. (appUser instanceOf User)
transaction.update(userRef, "companies", appUser.companies);
If I do so...I get
Invalid data. Unsupported type: ro.exemple.model.UserCompany
How can I serialise an User object so that I can deserialise it as such
User appUser = queryDocumentSnapshots.getDocuments().get(0).toObject(User.class);
Where queryDocumentSnapshots is the result of a query in my firestore db.
I know I can change from ArrayList to HashMap, but I wish to keep the List, and try to serialise and deserialise it, in order to obtain in firestore an array of objects.
if this serialization you must tag your class as Serializable..
public UserCompany extends Model implements Serializable
public class User extends Model implements Serializable
plus tag the class Model as well
I write a program that parse json and shows it in a listView.
Now i want to sort it but don't know how and fail. In program i have a List<PoolOfflineModal> alist = new ArrayList<>();
so modal are this;
public class PoolOfflineModal {
private int id;
private String name;
private int price;
private int priceWithoutDiscount;
private String tel;
private int discountPercent;
private String address;
private String photo;
}
and data simple is here http://hayat.cloudsite.ir/pools/pools.json
so i want to sort List ascending with price, so update ListView and i don't know...
another idea?! or solution?!
another way are exist to sort ListView from a column without sort list?!?
this is my last Comparator
public class MyComparator implements Comparator<PoolOfflineModal> {
#Override
public int compare(PoolOfflineModal lo, PoolOfflineModal ro) {
int result = 0;
if (way == "name") {
result = lo.getName().compareTo(ro.getName());
} else if (way == "price") {
result = lo.getPrice().compareTo(ro.getPrice());
} else if (way == "percent") {
result = lo.getDiscountPercent().compareTo(ro.getDiscountPercent());
}
return result;
}
}
List Object Like This:
List<PoolOfflineModal> alist = new ArrayList<>();
Comparator Class Like this:
public class MyComparator implements Comparator<PoolOfflineModal> {
#Override
public int compare(PoolOfflineModal o1, PoolOfflineModal o2) {
return o1.id.compareTo(o2.id);
}
}
Use Like this:
Collections.sort(alist, new MyComparator());
Hope it will helpful to you.
I have different packages in my app like this.
CansTypeObject class looks like this
public class CansTypeObject {
String productId;
String productName;
String productPrice;
String productReturnPrice;
String productImage;
}
Now, I want to access these strings from MainActivity
CansTypeObject object = new CansTypeObject();
But I cant. If I move the CansTypeObject class to the same package as that of MainActivity, I can access them. What is the solution for this?
The default scope is package-private. Use the public modifier on the String declaration
public String productId;
The only reason of this behavior is that you declared yours class Strings as package-protected strings. In Java this means, that this fields will be accessible only for classes in the same package.
There are several solutions for your problem.
The first (and the worst) - declare your fields as public strings, like this:
public String myField;
The second - create getters for your fields and declare your strings as private fields, like this:
private String myField;
public String getMyField() {
return myField;
}
Then, use this getters on your class object.
Hope, it helps.
You can define getter-setter method for the CansTypeObject class as follows for accessing them easily:
public class CansTypeObject {
String productId;
String productName;
String productPrice;
String productReturnPrice;
String productImage;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public String getProductReturnPrice() {
return productReturnPrice;
}
public void setProductReturnPrice(String productReturnPrice) {
this.productReturnPrice = productReturnPrice;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
}
for creating getter-setter method you can use shortcut key for
MAC - command + N
Windows - Alt + Insert
Another way is to open the class for which you have to make getter setter and then right click and from the context menu select Generate option
I am trying to save the arraylist of class objects into the ormlite database , but it is giving the error , java.lang.IllegalArgumentException: No fields have a DatabaseField annotation in class java.util.ArrayList
my code is
#DatabaseTable
public class ManageModelDetails {
#DatabaseField(generatedId = true)
private int id;
#DatabaseField(foreign = true, foreignAutoRefresh = true)
private ArrayList<ModelDetails> listModelDetails;
// ===============================================
public ManageModelDetails() {
super();
}
// ===============================================
public ManageModelDetails(int id, ArrayList<ModelDetails> listModelDetails) {
super();
this.id = id;
this.listModelDetails = listModelDetails;
}
// ===============================================
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setModelList(ArrayList<ModelDetails> listModelDetails) {
this.listModelDetails = listModelDetails;
}
public ArrayList<ModelDetails> getModelList() {
return listModelDetails;
}
}
I think you need to use Foreign Collections. Take a look here:
Foreign Collections
Another similar question
If you want to save an ArrayList of objects to ORMLite the easiest way is this:
#DatabaseField(dataType = DataType.SERIALIZABLE)
private SerializedList<MyObject> myObjects;
and to get my list of objects:
public List<MyObject> getMyObjects() {
return myObjects;
}
and here is SerializedList:
public class SerializedList<E> extends ArrayList<E> implements Serializable {
}
i just started to android prograamming and found nice tutorial by using imdb api. instead of using xml in this tutorial i would like to use json and for the recevied json i have a problem.
this is the person.json:
[
{
"score":1,
"popularity":3,
"name":"Brad Pitt",
"id":287,
"biography":"test",
"url":"http://www.themoviedb.org/person/287",
"profile":[
{
"image":{
"type":"profile",
"size":"thumb",
"height":68,
"width":45,
"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w45/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg",
"id":"4ea5cb8c2c0588394800006f"
}
},
{
"image":{
"type":"profile",
"size":"profile",
"height":281,
"width":185,
"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w185/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg",
"id":"4ea5cb8c2c0588394800006f"
}
},
{
"image":{
"type":"profile",
"size":"h632",
"height":632,
"width":416,
"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/h632/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg",
"id":"4ea5cb8c2c0588394800006f"
}
},
{
"image":{
"type":"profile",
"size":"original",
"height":1969,
"width":1295,
"url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/original/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg",
"id":"4ea5cb8c2c0588394800006f"
}
}
],
"version":685,
"last_modified_at":"2013-02-16 07:11:15 UTC"
}
]
my two object for them:
public class Person implements Serializable {
private static final long serialVersionUID = 6794898677027141412L;
public String score;
public String popularity;
public String name;
public String id;
public String biography;
public String url;
public String version;
public String lastModifiedAt;
public Profile profile;
}
public class Profile implements Serializable {
private static final long serialVersionUID = -8735669377345509929L;
public ArrayList<Image> imagesList;
}
public class Image implements Serializable {
private static final long serialVersionUID = -2428562977284114465L;
public String type;
public String url;
public String size;
public int width;
public int height;
}
ı couldnt figure out how to retrieve person list by using jackson object mapper.
when i use this one:
ObjectMapper mapper = new ObjectMapper();
Person person= mapper.readValue(jsonResponseString, Person.class);
i got:
02-16 18:34:48.010: W/System.err(376): com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.example.imdbsearcher.model.Person out of START_ARRAY token
02-16 18:34:48.180: W/System.err(376): at [Source: java.io.StringReader#40a81778; line: 1, column: 1]
02-16 18:34:48.554: W/System.err(376): at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:599)
02-16 18:34:48.830: W/System.err(376): at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:593)
i have changed the retrieve method with advice of Keith and crdnilfan.
but now i have a problem with the attribute of profile.
i realized that i am missing that one in person object and basicly i have created new profile object and moved imageList to this class.
i have updated POJO's as above.
but now i am getting the same error for the profile.
Can not deserialize instance of com.example.imdbsearcher.model.Profile out of START_ARRAY token
You need to deserialize the list, as your JSON is an array:
List<Person> people = mapper.readValue(
jsonResponseString, new TypeReference<List<Person >>(){});
However, after you do that you will have some additional deserialization errors because of the profile property in your JSON. Checkout: http://jackson.codehaus.org/1.5.7/javadoc/org/codehaus/jackson/annotate/JsonIgnoreProperties.html
Update:
public class Person implements Serializable
{
public List<Object> profile;
public String score;
public String popularity;
public String name;
public String id;
public String biography;
public String url;
public String version;
public String last_modified_at;
}
There are several ways to deal with this. This will give you a linked hash map for Profile.
Alternatively, if you control the JSON format, change the profile syntax to this:
"profile":[
image:...,
image:...
]
That's because you are trying to deserialize a list of Person.class, not one instance. Create another class like this
public class PersonList extends ArrayList<Person> {}
and then use
ArrayList<Person> people = mapper.readValue(jsonResponseString, PersonList.class);
The other two answers clearly explain the reason for the error, it would get rid off the error and it will parse Person object. But for me it failed to parse image objects. With below POJO we can parse the specified json completely, without any issues even in the absence of
#JsonIgnoreProperties
or
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
POJO definition:
public class PersonList extends ArrayList<Person> {}
public class Person implements Serializable {
private static final long serialVersionUID = 6794898677027141412L;
public String score;
public String popularity;
public String name;
public String id;
public String biography;
public String url;
public String version;
#JsonProperty(value="last_modified_at")
public String lastModifiedAt;
public List<Profile> profile;
}
public class Profile implements Serializable {
private static final long serialVersionUID = -8735669377345509929L;
#JsonProperty(value="image")
public Image imagesList;
}
public class Image implements Serializable {
private static final long serialVersionUID = -2428562977284114465L;
public String id;
public String type;
public String url;
public String size;
public int width;
public int height;
}
This should parse the json
String jsonResponseString = readJsonFile("person.json");
ObjectMapper mapper = new ObjectMapper();
PersonList person= mapper.readValue(jsonResponseString, PersonList.class);
or
List<Person> person= mapper.readValue(jsonResponseString,
new TypeReference<List< Person>>(){}); //if we use this we dont have to define PersonList class