Hi there i have this JSON i´m mapping the "Users" with gson but i need to consolidate the maps (in this example 2 but can be more) in only 1 Map or 1 List be cause i need to send the consolidate to a Custom Adapter, as you can see i had 2 list of users and i access to each list users and atributes without problem but i need to create just 1 map or list, is there anyway to consolidate that mutivalue maps in only one?
[{
"id": 999098,
"name": "Legendary Users",
"users": {
"98087ffg5": {
"Age": 20,
"name": "dighak"
},
"0987499gg8": {
"Age": 18,
"name": "kijhg"
},
"1231ghty56": {
"Age": 19,
"name": "ramn1"
}
}
},
{
"id": 999098,
"name": "Best Users",
"users": {
"12312bvf123": {
"Age": 20,
"name": "thispa"
},
"50827gh65": {
"Age": 21,
"name": "vista1"
}
}
}]
This is my Response.class
public class Response {
private int id;
private String name;
private Map<String,UsersBean> users = new LinkedHashMap<>();
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public Map<String,UsersBean> getUsers() {return users;}
public void setUsers(Map<String,UsersBean> users) {this.users = users;}
public static class UsersBean {
private int Age;
private String name;
public int getAge() {return Age;}
public void setAge(int Age) {this.Age = Age;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
}
I can access to each list of users like this
Response response;
response.get(0).getUsers().get("98087ffg5").getAge();
but i need an consolidate data of list of users with all the keys and respective values, can you help my with this? i need to create a new class o map and use for loop? for access to all like:
list/map.getUsers().get("98087ffg5").getAge();
Why not use an array or arrayList of your Response class?
For example, setting the JSON string:
String jsonString = new Gson().toJson(responseArray);
...and getting the array of responses from it:
Response[] responseArray = new Gson().fromJson(jsonString, Response[].class);
Related
I am trying to match a value in a list using variable and return the list if condition matches.
result =
{
"drives": [{
"id": "0AEz3mOyzyCb7Uk9PVA",
"name": "Dev-zz-SFJobs-2020-10"
}, {
"id": "0AMEHi1wsq-8FUk9PVA",
"name": "Dev-zz-SFJobs-2020-11"
},
],
"nextPageToken": "~!!~AI9FV7RVoBRduLEGDhuzy0aSZShRe4uSXy20zpCBTP2LFWCXS0c"
}
folderName = "Dev-zz-SFJobs-2020-10"
java code:
if(result.getDrives().contains(folderName))
{
return result;
} else {
}
I am trying above code, how can i achieve this?
This would work for you if you are using java 8+
Optional<Drives> value = result.getDrives().stream().filter(drive -> drive.getName().equals(folderName)).findAny();
if (value.isPresent()){
return result;
}else{
}
I am expecting your model class Drive contains two variables of type string namely "id" and "name"
public class Drives {
private String id;
private String name;
public Drives(String id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
I am making an app where I am using room as a database cache and fetching data from the server using retrofit2 and saving it in room database but after fetching from server data is unable to insert in room database.
Here is an exception it is showing:
This is my pojo class below:
#Entity(tableName = "Users")
public class User {
#NonNull
#PrimaryKey
#SerializedName("_id")
private String _id;
#ColumnInfo(name = "name")
#SerializedName("name")
#Expose
private String name;
#ColumnInfo(name = "age")
#SerializedName("age")
#Expose
private String age;
public User(){}
public User(#NonNull String _id,String name, String age) {
this._id = _id;
this.name = name;
this.age = age;
}
#NonNull
public String get_id() {
return _id;
}
public void set_id(#NonNull String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
JSON Response
[
{
"id": "5cf68fe7b439470017236249",
"name": "Rhea",
"age": "2"
},
{
"id": "5d09006696a8470cbc7c34a2",
"name": "Don",
"age": "10"
},
{
"id": "5d092d9858af5d22a80858bf",
"name": "Roman",
"age": "30"
},
{
"id": "5d09e9976f3bad18b8fa54a0",
"name": "Roman",
"age": "30"
},
{
"id": "5d09ea2ac127bd07b4b64f6f",
"name": "Roman",
"age": "30"
}
]
Someone please let me know what is happening wrong. Any hep would be appreciated.
chnage
#NonNull
#PrimaryKey
#SerializedName("_id") // key does not match with response key
private String _id;
to
#NonNull
#PrimaryKey
#SerializedName("id")
private String _id;
It seems that you have the id parameter named as "id" in your JSON while your model is waiting for "_id". Try removing that leading underscore symbol.
I think that one or more users id that you are fetching data from the server using retrofit2 is null, and because of that you can't insert into your local database
I have a file called persons.json:
[
{
"id": 1,
"name": "The Best",
"email": "thenextbigthing#gmail.com",
"birthDate": "1981-11-23"
},
{
"id": 2,
"name": "Andy Jr.",
"email": "usa#gmail.com",
"birthDate": "1982-12-01"
},
{
"id": 3,
"name": "JohnDoe",
"email": "gameover#gmail.com",
"birthDate": "1990-01-02"
},
{
"id": 4,
"name": "SomeOne",
"email": "rucksack#gmail.com",
"birthDate": "1988-01-22"
},
{
"id": 5,
"name": "Mr. Mxyzptlk",
"email": "bigman#hotmail.com",
"birthDate": "1977-08-12"
}
]
I'd like to parse this file into an ArrayList with FasterXML, possibly with it's ObjectMapper() function and then being able to access each value (id, name, etc.) individually as a String when iterating through the newly created ArrayList. How could I do that? I don't even know what kind of list I could/should use in order to get access to each value individually. I'm kind of stuck here. List<???>
First of all:
FasterXML uses Jackson underneath to parse/produce json.
Now: to use Jackson, first of all create a container object for the data of your json, which we will call Person
public class Person {
private int id;
private String name, email;
#JsonFormat
(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date birthDate;
//add here getters and setters ...
}
At this point, supposing you have pathToPersonsJsonFile as a string containing the path to your persons.json, you can use your file like this:
byte[] jsonData = Files.readAllBytes(Paths.get(pathToPersonsJsonFile));
ObjectMapper objectMapper = new ObjectMapper();
Person[] parsedAsArray = objectMapper.readValue(jsonData, Person[].class); //array
ArrayList<Persons> persons = new ArrayList<>(Arrays.asList(parsedAsArray)); //your list
Note: JsonFormat enables to declare which format that value has on your json.
First you should create POJO for storing info:
public class Person {
Long id;
String name;
String email;
#JsonFormat("yyyy-mm-dd")
Date birthDate;
...
}
next you should call:
List<Person> myObjects = new ObjectMapper().readValue(jsonInput, new TypeReference<List<Person>>(){});
This should be enough
ObjectMapper objectMapper = new ObjectMapper();
List<Person> list = objectMapper.readValue(new File("path_to_persons.json"), new TypeReference<List<Person>>(){});
public class Person {
private String id;
private String name;
private String email;
private String birthDate;
.....
}
1) First create class Person.java
2) Then read the persons.json file and create a JSONArray from it.
3) Then parse as given below:
class Person{
private int id;
private String name;
private String email;
private String birthDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
}
public List<Person> getPersonList(JSONArray dataArray){
List<Person> personList = new ArrayList<>();
for(int i=0; i<dataArray.length(); i++){
try {
JSONObject personJsonObject = dataArray.getJSONObject(i);
Person person = new Person();
if(personJsonObject.has("id") && !personJsonObject.isNull("id")){
person.setId(personJsonObject.getInt("id"));
}
if(personJsonObject.has("name") && !personJsonObject.isNull("name")){
person.setName(personJsonObject.getString("name"));
}
if(personJsonObject.has("email") && !personJsonObject.isNull("email")){
person.setEmail(personJsonObject.getString("email"));
}
if(personJsonObject.has("birthDate") && !personJsonObject.isNull("birthDate")){
person.setBirthDate(personJsonObject.getString("birthDate"));
}
personList.add(person);
}catch (JSONException e){
}
}
return personList;
}
4) Then use this list wherever you want.
Hi i'm trying to learn android and now implementing the retrofit 1.9 for my rest POST and GET request can somebody help me on how to model given json objects and strings? im very confused on some tutorials I have learned how make a pojo for this json object
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
}}]}
Using this model
Contacts.class
public class Contacts {
#SerializedName("contacts")
#Expose
private List<Contact> contacts = new ArrayList<Contact>();
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
and Contact.class for the objects
public class Contact {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("email")
#Expose
private String email;
#SerializedName("address")
#Expose
private String address;
#SerializedName("gender")
#Expose
private String gender;
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 getEmail() {return email;}
public void setEmail(String email) {this.email = email;}
public String getAddress() {return address;}
public void setAddress(String address) {this.address = address;}
public String getGender() {return gender;}
public void setGender(String gender) {this.gender = gender;}}
And Calling the list using this on my MainActivity.class
private void getContacts() {
final ProgressDialog loading = ProgressDialog.show(this, "Fetching Data", "Please wait...", false, false);
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(ROOT_URL).build();
ContactsAPI api = adapter.create(ContactsAPI.class);
api.getContacts(new Callback<Contacts>() {
#Override
public void success(Contacts contacts, Response response) {
loading.dismiss();
List<Contact> contactList = contacts.getContacts();
String[] items = new String[contactList.size()];
for (int i = 0; i < contactList.size(); i++) {
items[i] = contactList.get(i).getName();
}
ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.simple_list,R.id.textview, items);
//Setting adapter to listviesw
listView.setAdapter(adapter);
}
#Override
public void failure(RetrofitError error) {
}
});
}
THen my Question is how should i make a model out of this array Object?
{
"-KNea90tV5nZlkeqxc3Q": {
"accountName": "Mark Papyrus",
"accountNumber": "12435656443",
"accountType": "Peso Savings"
},
"-KNeaPmBoTXV4mQC6cia": {
"accountName": "Mark Dremeur",
"accountNumber": "12435656444",
"accountType": "Peso Checking"
}
i found it confusing how to make models and difference of given json arrays pls guide me thanks.
I think me and you are having the same problems but I am stuck so I can help you as far as I can . First you cannot use jsonschema2pojo.org to create the pojo class you need to use hashmap from what I understand "-KNea90tV5nZlkeqxc3Q": is a key but 1 of the classes should be the following ( also the accountype since its a type you can use enum but it would be bit harder to code)
public class Account {
private String accountName;
private String accountNumber;
private String accountType;
public Account() {
}
public String getAccountName() {return accountName;}
public void setAccountName(String accountName) {
this.accountName=accountName;}
// *** repeat for the accountnumber and accountype
}
if the key "KNea90tV5nZlkeqxc3Q" is dynamic and need to capture them, you musto to use a hashmap in your model to catch them correctly.
check this issue it could be useful:
Parse Dynamic Key Json String using Retrofit
Using Jackson, I know that I can include / exclude a property from serialization for a view by using #JsonView.
How can I vary a JSON property's value by view?
e.g., I might want a property's value in view A to be the whole object, in view B to be the object with certain properties filtered out, in view C, I just want it to be the "id" (no object), and in view D, I might want it to be the "name" (no object):
// view A JSON
{
"prop": {"id": 123, "name": "abc", "description": "def"}
}
// view B JSON
{
"prop": {"id": 123, "name": "abc"}
}
// view C JSON
{
"prop": 123
}
// view D JSON
{
"prop": "abc"
}
You can probably achieve this using generics but you also need to know in advance what concrete class to use, e.g.:
public static void main(String[] args) throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final MyStuff<Prop> myStuff = mapper.readValue("{\"prop\": {\"id\": 123, \"name\": \"abc\", \"description\": \"def\"}}", MyStuff.class);
final MyStuff<String> myStuff1 = mapper.readValue("{\"prop\": \"abc\"}", MyStuff.class);
final MyStuff<Integer> myStuff2 = mapper.readValue("{\"prop\": 123}", MyStuff.class);
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Prop {
private Integer id;
private String name;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class MyStuff<T> {
private T prop;
public T getProp() {
return prop;
}
public void setProp(T prop) {
this.prop = prop;
}
}
so not sure if this is what you want.