I have an unsorted array of players that came through a JSON response:
"participants": [{
"participant": {
"rank": 3,
"name": "I Tied for third",
}
}, {
"participant": {
"rank": 1,
"name": "I got first",
}
}, {
"participant": {
"rank": 3,
"name": "Also tied for third",
}
}, {
"participant": {
"rank": 2,
"name": "I got second",
}
}]
I would like to sort this somehow so that I can eventually print out both the player's name, and their rank... but in order.
I thought about possibly putting the results of the array into a TreeMap, but then I realised that TreeMaps require unique array keys and that wouldn't work:
Map<Integer, String> players = new TreeMap<>();
for (int i = 0; i < participants.length(); i++) {
JSONObject object = participants.getJSONObject(i);
JSONObject participant = object.getJSONObject("participant");
players.put(participant.getInt("rank"), participant.getString("name"));
}
So is there another way to get this done?
With #VivekMishra helping, I was able to get it working:
ArrayList<PlayerObject> players = new ArrayList<>();
for (int i = 0; i < participants.length(); i++) {
JSONObject object = participants.getJSONObject(i);
JSONObject participant = object.getJSONObject("participant");
players.add(new PlayerObject(participant.getInt("rank"), participant.getString("name")));
}
Collections.sort(players);
With:
class PlayerObject implements Comparable<PlayerObject> {
private int rank;
private String name;
public PlayerObject(int r, String n) {
setRank(r);
setName(n);
}
public int compareTo(PlayerObject other) { return rank - other.rank; }
public int getRank() { return rank; }
public void setRank(int text) { rank = text; }
public String getName() { return name; }
public void setName(String text) { name = text; }
}
Related
I'm trying to obtain an ArrayList of object and initialize it in a wrapper class,
this is my request;
RestTemplate restTemplate = new RestTemplate();
Inventory i = restTemplate.getForObject("http://localhost:8082/items",Inventory.class);
my response handler;
#RequestMapping(value ="/items", method = RequestMethod.GET)
public ArrayList<Item> getItems() {
return ItemList.getItemList();
}
my ItemList class,
public class ItemList{
//to keep a list of globally available list of orders with the type Item.class objects
private static ArrayList<Item> itemList;
public static ArrayList<Item> getItemList() {
return itemList;
}
public static void setItemList(ArrayList<Item> itemList) {
ItemList.itemList = itemList;
}
public static Item getItemById(String id) throws NoSuchItem {
ArrayList<Item> temp = ItemList.getItemList();
for(Item x:temp){
if(x.getId().equals(id))
return x;
}
throw new NoSuchItem();
}
};
My Inventory class,
public class Inventory{
private ArrayList<Item> itemList;
public ArrayList<Item> getRandomList(int size) {
ArrayList<Item> items = new ArrayList<Item>();
ArrayList<Item> temp = this.itemList;
if(size>=itemList.size()){
return itemList;
}
else{
Random rand = new Random();
for(int i=0;i<size;i++){
int j = rand.nextInt(temp.size());
Item random = temp.get(j);
random.generateQuantity();
items.add(random);
temp.remove(random);
}
}
return items;
}
public ArrayList<Item> getItemList() {
return itemList;
}
public void setItemList(ArrayList<Item> itemList) {
this.itemList = itemList;
}
};
and finally my Item class,
public class Item {
private String name ;
private String supplier ;
private String weight;
private String id ;
private String location = "not assigned" ;
private int quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getQuantity() {
return quantity;
}
public void generateQuantity(){
Random rand = new Random();
int i = rand.nextInt(100);
if(i<3){
this.quantity = 3;
}
else if(i<33){
this.quantity = 2;
}
else{
this.quantity = 1;
}
}
};
I'm building a microservice project using springboot, my response and ItemList class exist in one service , request and Inventory in the next service and the Item class on both the services, But when i run the method i get an JSON parse error: Cannot deserialize instance of ServiceA.Inventory out of START_ARRAY token, What am i doing wrong here?
PS - a sample response the /items endpoint returns ,
[
{
"name": "Mars",
"supplier": "Nestle",
"weight": "1",
"id": "mars",
"location": "not asssigned"
},
{
"name": "Kit Kat",
"supplier": "Nestle",
"weight": "1",
"id": "kitkat",
"location": "not asssigned"
},
{
"name": "Double Decker",
"supplier": "Nestle",
"weight": "1",
"id": "dd",
"location": "not asssigned"
}
]
According to yout JSON there is no Inventory in the response. So when you do this:
Inventory i = restTemplate.getForObject("http://localhost:8082/items", Inventory.class);
it complains because your response actually has an array (or list) of Item. Object inventory cannot be instantiated from an arrray. Try this:
Item[] items = restTemplate.getForObject("http://localhost:8082/items", Item[].class);
and it should work.
To have class Inventory deserialized your JSON response should be something like:
{
itemList: [
{
"name": "Mars",
"supplier": "Nestle",
"weight": "1",
"id": "mars",
"location": "not asssigned"
},
...
]
}
But note: There is also a problem with your ItemList. Anyway that is another topic because you should first think whhether your response JSON is ok or not.
I think you need to add a no args constructor to the Item class.
How can I parse JSON in the following format. I need to apply a loop to get the data from the keys 'n1', 'n2', 'n3' etc. I generated POJO classes, but since 'n1', 'n2', 'n3' etc is not an array, I cannot use a loop.
{
"data": {
"n1": {
"bla": "0",
"bla2": "0",
"bla3": [
{
"zzz1": "0",
"zzz2": "0",
"zzz3": [
"0",
"0",
"0"
]
}
]
},
"n2": {
"bla": "0",
"bla2": "0",
"bla3": [
{
"zzz1": "0",
"zzz2": "0",
"zzz3": [
"0",
"0",
"0"
]
}
]
},
"n3": {
"bla": "0",
"bla2": "0",
"bla3": [
{
"zzz1": "0",
"zzz2": "0",
"zzz3": [
"0",
"0",
"0"
]
}
]
}
}
}
POJO:
public class MyPojo
{
ArrayList<Data> data = new ArrayList<>();
public ArrayList<Data> getData ()
{
return data;
}
class Data
{
private N1 n1;
private N3 n3;
private N2 n2;
public N1 getN1 ()
{
return n1;
}
public N3 getN3 ()
{
return n3;
}
public N2 getN2 ()
{
return n2;
}
}
class N1
{
private String bla;
private String bla2;
private ArrayList<Bla3> bla3 = new ArrayList<>();
public String getBla ()
{
return bla;
}
public String getBla2 ()
{
return bla2;
}
public ArrayList<Bla3> getBla3 ()
{
return bla3;
}
}
class N2
{
private String bla;
private String bla2;
private ArrayList<Bla3> bla3 = new ArrayList<>();
public String getBla ()
{
return bla;
}
public String getBla2 ()
{
return bla2;
}
public ArrayList<Bla3> getBla3 ()
{
return bla3;
}
}
class N3
{
private String bla;
private String bla2;
private ArrayList<Bla3> bla3 = new ArrayList<>();
public String getBla ()
{
return bla;
}
public String getBla2 ()
{
return bla2;
}
public ArrayList<Bla3> getBla3 ()
{
return bla3;
}
}
class Bla3
{
private String zzz1;
private String zzz2;
private String[] zzz3;
public String getZzz1 ()
{
return zzz1;
}
public String getZzz2 ()
{
return zzz2;
}
public String[] getZzz3 ()
{
return zzz3;
}
}
}
POJO I did myself. Is he correct? Android Studio does not issue errors, but the cycle does not work, since it is not an array. The error 'Expected BEGIN_ARRAY but was BEGIN_OBJECT' appears.
If you're using Jackson as the JSON parser you can use the #JsonAnySetter annotation to get called for each of the properties not in your class. This would allow you to perform the same action for each property - effectively looping around them.
Simplifying your json to...
{
"n1": {"a":"one"},
"n2": {"a":"two"},
"n3": {"a":"three"}
}
given a class Data to map the values of n1, n2 and n3 into
public class Data {
private String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
Then you could use the #JsonAnySetter like so to populate a map, the keys would be n1, n2, n3 and values would be Data objects with a = one, two and three
public class MyPojo
{
Map<String, Data> dataMap = new HashMap<>();
public List<Data> getDataAsAList () {
return new ArrayList<Data>(dataMap.values());
}
#JsonAnySetter
public void addData(String fieldName, Data value) {
dataMap.put(fieldName, value);
}
}
{
"status": true,
"message": [
{
"ID": 1,
"TFrom": "b",
"TTo": "c"
},
{
"ID": 2,
"TFrom": "b",
"TTo": "c"
},
{
"ID": 3,
"TFrom": "b",
"TTo": "c"
}
]
}
This is my JSON result, I'm using Android/Java and what I want is to get each object in the "message" array separated in an array, because each one of them should be in a list item.
Which means my ListView is going to view the "message" content in lists.
It's more like this:
list1= [{"ID": 1, "TFrom": "b", "TTo": "c"}]
list2= [{"ID": 2, "TFrom": "b", "TTo": "c"}]
Message Object Class:
public class MessagesObject {
boolean status;
List<AMessage> message;
public List<AMessage> getMessage() {
return message;
}
public void setMessage(List<AMessage> message) {
this.message = message;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
AMessage Class:
public class AMessage {
int ID;
String TFrom;
String TTo;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getTFrom() {
return TFrom;
}
public void setTFrom(String TFrom) {
this.TFrom = TFrom;
}
public String getTTo() {
return TTo;
}
public void setTTo(String TTo) {
this.TTo = TTo;
}
}
Usage :
String json="you json string";
MessagesObject messagesObject = new Gson().fromJson(jsonToParse, MessagesObject.class);
Ref Gson :
implementation 'com.google.code.gson:gson:2.8.2'
Output:
I'm not sure what you really want, but if you really would like to convert an array into list of arrays, ie.
[1, 2, 3] => [[1], [2], [3]]
You can use this code as a starting point.
List<List<T>> YOUR_LIST_OF_LISTS = message.stream().map((e) -> {
ArrayList<T> temp = new ArrayList<>();
temp.add(e);
return temp;
}).collect(Collectors.toList());
Replace T with some datatype you want, in your case probably JSONObject.
Not android specific, just java codes. I'm not sure why you would want to do something like this tho. Comment below if this is not what you intended.
JSONObject heroObject = data.getJSONObject("favorite");
JSONArray jarray=heroObject.getJSONArray("message");
ArrayList<HashMap<String,String>> array=new ArrayList<>();
//now looping through all the elements of the json array
for (int i = 0; i < jarray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = jarray.getJSONObject(i);
HashMap<String,String> inner=new HashMap<String, String>();
inner.put("id", heroObject.getString("ID"));
inner.put("from", heroObject.getString("TFrom"));
inner.put("to", heroObject.getString("TTo"));
array.add(inner);
}
Use gson library. check below how to implement in project.
build.gradle
implementation 'com.google.code.gson:gson:2.7'
Then create MessageModel.java and MessageBaseModel.java.
MessageModel.java
public class MessageModel {
#SerializedName("ID")
int id;
#SerializedName("TFrom")
String tFrom;
#SerializedName("TTo")
String tTo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String gettFrom() {
return tFrom;
}
public void settFrom(String tFrom) {
this.tFrom = tFrom;
}
public String gettTo() {
return tTo;
}
public void settTo(String tTo) {
this.tTo = tTo;
}
}
MessageBaseModel.java
public class MessageBaseModel {
#SerializedName("status")
boolean status;
#SerializedName("message")
ArrayList<MessageModel> messageModels = new ArrayList<>();
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public ArrayList<MessageModel> getMessageModels() {
return messageModels;
}
public void setMessageModels(ArrayList<MessageModel> messageModels) {
this.messageModels = messageModels;
}
}
Use below code in your main activity:(note: result is your JSON result)
MessageBaseModel messageBaseModel=new Gson().fromJson(result.toString() , MessageBaseModel.class);
ArrayList<MessageModel> messageModels = MessageBaseModel.getMessageModels();
Check below example to get the output:
messageModels.get(0) is your first message object
messageModels.get(0).getId()=1
messageModels.get(0).gettFrom()=b
messageModels.get(1).getId()=2
messageModels.get(2).getId()=3
Sorry for my english.
Try this
List<Map<String,String>> list = new ArrayList<>();
try
{
JSONArray messageArray = response.getJSONArray("message");
for (int i = 0;i<messageArray.length(); i++)
{
Map<String,String> map = new HashMap<>();
JSONObject jsonObject = messageArray.getJSONObject(i);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext())
{
String key = keys.next();
String value = jsonObject.getString(key);
map.put(key,value);
}
list.add(map);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
I have JSON like this
{
"data":
[
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
}
]
}
]
}
I am using JSON Object to de-Serialize the data
this is what i am trying to
JSONObject jsonObj = new JSONObject(jsonStr);
String first = jsonObj.getJSONObject("data").getString("name");
System.out.println(first);
But a Cant seem to get the name or anything
Not sure what i am doing wrong?
and then i am trying to display it into a listview but haven't got to that part yet
data is a JSON Array, not a JSONObject
try: jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
also note the difference between getString and optString, if you don't want an exception on null use the later.
First parse your Json from below method,
private ArrayList<String> getStringFromJson(String jsonStr)
{
ArrayList<String> mNames = new ArrayList<String>();
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
mNames= row.getString("Name");
}
return mNames;
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
} catch (JSONException e) {
}
Data is a json array. Use getJsonObject for json objects.
Refer to this example to create a ListView and populate it's adapter with data from a json object.
Use GSON instead JSON. Hope it helps you.
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<Data> datas= new ArrayList<Data>();
datas= Arrays.asList(gson.fromJson(jsonString, Data[].class));
public class Ingredients {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
public class Data {
private int id;
private String Name;
private String Image;
private String Category;
private String Method;
public List<Ingredients> getIngredients() {
return Ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
Ingredients = ingredients;
}
private List<Ingredients> Ingredients = new ArrayList<Ingredients>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
}
I have got the JSON as below
{
"brands": [
{
"name": "ACC",
"quantity": "0",
"listedbrandID": 1,
"status": "0"
}
],
"others": [
{
"name": "dd",
"quantity": "55",
"listedbrandID": 1
},
{
"name": "dd",
"quantity": "55",
"listedbrandID": 1
}
]
}
I am trying to remove the dupcate JSON objects from the Others array
I was trying it this way
String JSON = "{
"brands": [
{
"name": "ACC",
"quantity": "0",
"listedbrandID": 1,
"status": "0"
}
],
"others": [
{
"name": "dd",
"quantity": "55",
"listedbrandID": 1
},
{
"name": "dd",
"quantity": "55",
"listedbrandID": 1
}
]
}" ;
JSONObject json_obj = new JSONObject(json);
JSONArray array = json_obj.getJSONArray("others");
HashSet<Others> map = new HashSet<Others>();
for (int k = 0; k < array.length(); k++) {
Others otherbrands = new Others();
String name = array.getJSONObject(k).getString("name");
String quantity = array.getJSONObject(k).getString("quantity");
String listedbrandID = array.getJSONObject(k).getString("listedbrandID");
if(name!=null && !name.trim().equals(""))
{
otherbrands.setName(name);
otherbrands.setQuantity(quantity);
otherbrands.setListedbrandID(listedbrandID);
map.add(otherbrands);
}
}
for (int k = 0; k < array.length(); k++)
{
String name = array.getJSONObject(k).getString("name");
System.out.println(name);
if(!map.contains(name.trim()))
{
array.remove(k);
}
}
System.out.println(json_obj);
}
}
import java.util.Arrays;
public class Others {
private String name ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getListedbrandID() {
return listedbrandID;
}
public void setListedbrandID(String listedbrandID) {
this.listedbrandID = listedbrandID;
}
private String quantity ;
private String listedbrandID ;
#Override
public boolean equals (Object other)
{
if (!(other instanceof Others))
return false;
Others ob = (Others) other;
return name.equals(ob.name) &&
quantity.equals(ob.quantity);
}
#Override
public int hashCode ()
{
return Arrays.hashCode(new String[]{quantity,name});
}
}
But its printing the entire JSON
There are some issues with your code:
System.out.println(json_obj); is printing your initial JSON object, you do not seem to be iterating over the set and printing its content. Try:
for(Other other : map) System.out.println("Name : " + other.getName() + " ...");
I think you need to add listedbrandID in your equals method.
To get JSON with only the unique items, you could simply emit the resultant HashMap. Please refer to this previous SO question for more information.