{
"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();
}
Related
My json string is:
{
"recordsTotal":1331,
"data":[
{
"part_number":"3DFN64G08VS8695 MS",
"part_type":"NAND Flash",
"id":1154,
"manufacturers":[
"3D-Plus"
]
},
{
"part_number":"3DPM0168-2",
"part_type":"System in a Package (SiP)",
"id":452,
"manufacturers":[
"3D-Plus"
]
},
{
"part_number":"3DSD1G16VS2620 SS",
"part_type":"SDRAM",
"id":269,
"manufacturers":[
"3D-Plus"
]
}
]
}
This code lets me access the two highest level elements:
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
System.out.println("data : " + jsonObject.get("data"));
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
But what I want to do is iterate over all the objects inside "data" and create a list of part_numbers. How do I do that?
JsonArray is an Iterable<JsonElement>. So you can use for in loop.
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
final JsonArray data = jsonObject.getAsJsonArray("data");
System.out.println("data : " + data);
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
List<String> list = new ArrayList<String>();
for (JsonElement element : data) {
list.add(((JsonObject) element).get("part_number").getAsString());
}
Suppose class Name for Json Model is Example.
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Example {
#SerializedName("recordsTotal")
private Integer recordsTotal;
#SerializedName("data")
private List<Datum> data = null;
public Integer getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(Integer recordsTotal) {
this.recordsTotal = recordsTotal;
}
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
}
And suppose List of Data class name is Datum :-
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Datum {
#SerializedName("part_number")
private String partNumber;
#SerializedName("part_type")
private String partType;
#SerializedName("id")
private Integer id;
#SerializedName("manufacturers")
private List<String> manufacturers = null;
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartType() {
return partType;
}
public void setPartType(String partType) {
this.partType = partType;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getManufacturers() {
return manufacturers;
}
public void setManufacturers(List<String> manufacturers) {
this.manufacturers = manufacturers;
}
}
And then through Gson library we can convert json to java Model :
Example example = new Gson().fromJson(jsonString, new TypeToken<Example>() {}.getType());
Now we can get list of data though example model :-
List<Datum> dataList = example.getData();
From dataList you can traverse and get all info.
If partNmber List we need then we can get in this way :-
List<String> partNumberList = new ArrayList<>();
for (Datum data : dataList) {
partNumberList.add(data.getPartNumber());
}
The given code will not guaranteed to 100% equivalent but it will help you to work.
First you have to create the class for your data objects:
class mydata {
public String part_name;
public String part_type;
public int Id;
public String manufacturers;
}
Your main method should look like
public static void main(String[] args) {
JSONObject obj = new JSONObject();
List<mydata> sList = new ArrayList<mydata>();
mydata obj1 = new mydata();
obj1.setValue("val1");
sList.add(obj1);
mydata obj2 = new mydata();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
}
For futher exploration you can use that link:
https://gist.github.com/codebutler/2339666
Im using the following code to put up a json array within json object;
import org.json.JSONObject;
public class PollingPoJo {
int id;
String topic;
String description;
String pollItem1;
String pollItem2;
String pollItem3;
String pollItem4;
ArrayList<String> pollingItem ;
public PollingPoJo(int id, String topic, String description, String pollItem1, String pollItem2, String pollItem3,
String pollItem4) {
super();
this.id = id;
this.topic = topic;
this.description = description;
this.pollItem1 = pollItem1;
this.pollItem2 = pollItem2;
this.pollItem3 = pollItem3;
this.pollItem4 = pollItem4;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPollItem1() {
return pollItem1;
}
public void setPollItem1(String pollItem1) {
this.pollItem1 = pollItem1;
}
public String getPollItem2() {
return pollItem2;
}
public void setPollItem2(String pollItem2) {
this.pollItem2 = pollItem2;
}
public String getPollItem3() {
return pollItem3;
}
public void setPollItem3(String pollItem3) {
this.pollItem3 = pollItem3;
}
public String getPollItem4() {
return pollItem4;
}
public void setPollItem4(String pollItem4) {
this.pollItem4 = pollItem4;
}
#Override
public String toString() {
pollingItem = new ArrayList<>();
pollingItem.add(pollItem1);
pollingItem.add(pollItem2);
pollingItem.add(pollItem3);
pollingItem.add(pollItem4);
String jObj = new JSONObject().put("id",id)
.put("topic", topic)
.put("description", description)
.put("pollingItems", pollItem1).toString();
return jObj;
}
}
Later on Im using the following code to generate the response.
#POST
#Path("polling")
#Produces(MediaType.APPLICATION_JSON)
public static String getCurrentPoll() {
ArrayList<PollingPoJo> output = new ArrayList<PollingPoJo>();
try {
Connection connection = MyResource.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM POLLING order by id desc limit 1 ");
output = new ArrayList<PollingPoJo>();
while (rs.next()) {
PollingPoJo trending = new PollingPoJo(rs.getInt("ID"), rs.getString("TOPIC"), rs.getString("DESCRIPTION"),
rs.getString("ITEM1"), rs.getString("ITEM2"), rs.getString("ITEM3"),
rs.getString("ITEM4"));
output.add(trending);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
But the resulting json response does not contain json within it. Though I have embedded a array list within toString , it is not showing up. How can I be able to sort this out?
Following is the expected sample response,
{ "topic": "Fruits", "description":
"My favourite fruits", "id": 1,
"polling_items": [
"Item 1",
"Item 2",
"Item 3" ] }
but it is throwing the following response,
[ {
"topic": "Fruits",
"description": "My favourite fruits",
"id": 1,
"pollingItems": "item1" } ]
As you could see, pollingitems contains no json array. How can I be able to sort this out?
In your PollingPoJo, you should have a collection with name polling_items. And in the constructor of PollingPoJo, add the 3,4,5,6 parameters to this collection.
I am able to parse everything i need, except for the target_id's in the field_exercis_arc. I get the nid, title and body. Not sure how to get the id's in the field_exercis_arc.
The JSON
[{
"nid": "26",
"title": "Question test",
"body": "xcvxcv",
"field_exercis_arc": ["25","27"]
}]
The Code
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<ExerciseModel> exerciseModelList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
title_exi = finalObject.getString("title");
text_exi = finalObject.getString("body");
//This part is working.
ExerciseModel exerciseModel = new ExerciseModel();
exerciseModel.setTitle(finalObject.getString("title"));
exerciseModel.setNid(finalObject.getInt("nid"));
exerciseModel.setBody(finalObject.getString("body"));
//Problem with this part, not getting the target_id's.
List<ExerciseModel.Exer> exerList = new ArrayList<>();
for(int j=0; j<finalObject.getJSONArray("field_exercis_arc").length(); j++){
ExerciseModel.Exer exercis = new ExerciseModel.Exer();
exercis.setTarget_id(finalObject.getJSONArray("field_exercis_arc").getJSONObject(j).getString("target_id"));
exerList.add(exercis);
}
exerciseModel.setExerList(exerList);
exerciseModelList.add(exerciseModel);
mDB.saveRecordEX(exerciseModel);
}
The model for the field_exercis_arc and target_id's fields
private List<Exer> exerList;
public List<Exer> getExerList() {
return exerList;
}
public void setExerList(List<Exer> exerList) {
this.exerList = exerList;
}
public static class Exer{
private String target_id;
public String getTarget_id() {
return target_id;
}
public void setTarget_id(String target_id) {
this.target_id = target_id;
}
}
Thanks in advance
I recommend you to use GSON library to get result from JSON. For that you will need Java class in order to parse result to object. For this you can use JSON to Java Class conversion here.
For you example classes would be:
public class Und
{
private String value;
public String getValue() { return this.value; }
public void setValue(String value) { this.value = value; }
}
public class Body
{
private ArrayList<Und> und;
public ArrayList<Und> getUnd() { return this.und; }
public void setUnd(ArrayList<Und> und) { this.und = und; }
}
public class Und2
{
private String target_id;
public String getTargetId() { return this.target_id; }
public void setTargetId(String target_id) { this.target_id = target_id; }
}
public class FieldExercisArc
{
private ArrayList<Und2> und;
public ArrayList<Und2> getUnd() { return this.und; }
public void setUnd(ArrayList<Und2> und) { this.und = und; }
}
public class RootObject
{
private String vid;
public String getVid() { return this.vid; }
public void setVid(String vid) { this.vid = vid; }
private String uid;
public String getUid() { return this.uid; }
public void setUid(String uid) { this.uid = uid; }
private String title;
public String getTitle() { return this.title; }
public void setTitle(String title) { this.title = title; }
private Body body;
public Body getBody() { return this.body; }
public void setBody(Body body) { this.body = body; }
private FieldExercisArc field_exercis_arc;
public FieldExercisArc getFieldExercisArc() { return this.field_exercis_arc; }
public void setFieldExercisArc(FieldExercisArc field_exercis_arc) { this.field_exercis_arc = field_exercis_arc; }
private String cid;
public String getCid() { return this.cid; }
public void setCid(String cid) { this.cid = cid; }
private String last_comment_timestamp;
public String getLastCommentTimestamp() { return this.last_comment_timestamp; }
public void setLastCommentTimestamp(String last_comment_timestamp) { this.last_comment_timestamp = last_comment_timestamp; }
}
You can convert result to RootObject. Fox example:
String json = "{\"vid\": \"26\",\"uid\": \"1\",\"title\": \"Question test\",\"body\": {\"und\": [{\"value\": \"xcvxcv\"}]},\"field_exercis_arc\": {\"und\": [{\"target_id\": \"25\"},{\"target_id\":\"27\"}]},\"cid\": \"0\",\"last_comment_timestamp\": \"1472217577\"}";
RootObject object = new Gson().fromJson(json, RootObject.class);
System.out.println("Title is: "+object.getTitle() );
Result is:
Title is: Question test
After this you can use your object to get any value from your JSON.
Also you should know that your JSON is not valid. You have commas on two places that should not exists. In string i gave you above those are fixed. You should check you JSON with: JSON Formatter
Use below code :
exercis.setTarget_id(finalObject.getJSONArray("field_exercis_arc").getString(j));
JsonArray fieldArray=yourJsonObject.getJsonArray("field_exercis_arc");
for(int i=0;i<fieldArray.length;i++){
fieldArray.getString(i);
}
TO the parse the JSON you have to do it like this.
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
String title = finalObject.getString("title");
String body = finalObject.getString("body");
JSONArray arr = finalObject.getJSONArray("field_exercis_arc");
for(int x=0; x < arr.length(); x++){
String val = arr.getString(x);
}
}
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 a json object as like this:
[
{
"created_at": "2014-07-01 5:01:10",
"status": "in progress",
"device_id": "1234",
"order_details": [
{
"item_id": 1,
"quantity": 2
},
{
"item_id": 2,
"quantity": 3
}
]
}
]
And in java I have two classes order and order details as like this:
1) Order.java
package dto;
import java.util.ArrayList;
public class Order
{
int order_id;
String created_at;
String status;
String device_id;
ArrayList<Order_details> orderList= new ArrayList<Order_details>();
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDevice_id() {
return device_id;
}
public void setDevice_id(String device_id) {
this.device_id = device_id;
}
public ArrayList<Order_details> getOrderList() {
return orderList;
}
public void setOrderList(ArrayList<Order_details> orderList) {
this.orderList = orderList;
}
public void attachOrderDetails(ArrayList<Order_details> member) {
this.orderList = member;
}
}
2) Order_details.java
package dto;
public class Order_details
{
int item_id;
int quantity;
String item_name;
double price;
public int getItem_id()
{
return item_id;
}
public void setItem_id(int item_id)
{
this.item_id = item_id;
}
public int getQuantity()
{
return quantity;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public String getItem_name()
{
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name = item_name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
now i want to convert above json object to the object of order class
To achieve this i have tried it:
Order order= new Order();
order= gs.fromJson(json,Order.class);
System.out.println("order"+order);
but it throws exception as follows:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapte rFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:791)
at com.google.gson.Gson.fromJson(Gson.java:757)
at com.google.gson.Gson.fromJson(Gson.java:706)
at com.google.gson.Gson.fromJson(Gson.java:678)
Please, help me out to convert my json to my java object.
The first [ in your json says its holding an array or Order objects. So you need to make a list of orders rather than a single order class.
List<Order> order = new ArrayList<Order>();
order = gs.fromJson(json, order.getClass());
System.out.println("order" + order);
Or using type token as
List<Order> order = new ArrayList<Order>();
Type listType = new TypeToken<List<Order>>() {}.getType();
order = gs.fromJson(json, listType);
System.out.println("order" + order);
Alternatively to work with your code directly you need to modify your json to
{
"created_at": "2014-07-01 5:01:10",
"status": "in progress",
"device_id": "1234",
"order_details": [
{
"item_id": 1,
"quantity": 2
},
{
"item_id": 2,
"quantity": 3
}
]
}
When you are using GSON,then you should be more aware of case sensitive w.r.t key name and variable name.
either change variable name to
ArrayList<Order_details> order_details= new ArrayList<Order_details>(); instead of
ArrayList<Order_details> orderList= new ArrayList<Order_details>();
or
change json key name to orderList instead of order_details
Your JSON string can not cast directly to your class because your json contain array of the parameters of class Order and to convert it into class object you need list of Order class so that this array can be converted to list of Order.
For that you need to take List<Order> of Order class as shown below :
List<Order> orderList = new ArrayList<Order>();
Type listType = new TypeToken<List<Order>>(){}.getType();
orderList = json.fromJson(jsonStr, listType);
May this will help you.