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
Related
for example I have a json object like this:
{
"pic":"1.jpg",
"products":[
{
"id":1,
"pic":"4.jpg"
}
]
}
now I want to fetch all pic key inside an array or a list.
the result must be: ["1.jpg","4.jpg"]
There is a simple solution for this in jackson library.
String value = "{\"pic\":\"1.jpg\",\"products\":[{\"id\":1,\"pic\":\"4.jpg\"}]}";
JsonNode jsonNode = new ObjectMapper().readTree(value);
System.out.println(jsonNode.findValuesAsText("pic"));
You can add jackson by using following maven dependency.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
You can also pass file, inputstream to readTree().
Please try this code:
//define a list which will contain pic names
List<String> picList = new ArrayList<>();
try {
//jsonMap: your json object variable name
String picName = (String) jsonMap.get("pic");
picList.add(picName);
List<Map<String, Object>> products = (List<Map<String, Object>>) jsonMap.get("products");
for (Map<String, Object> product : products) {
String pic = (String) product.get("pic");
picList.add(pic);
}
System.out.println("=====List of pics===="+picList);
} catch (Exception e) {
}
It would be better if you parse the json to a POJO class. You can use Gson to convert json string to below Data class object.
String jsonString = "you json string here"
Data object = Gson().fromJson(jsonString, Data.class)
Now you have the object and can get product list from which you can iterate and get "pic" values.
Below is the class
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
#SerializedName("pic")
#Expose
private String pic;
#SerializedName("products")
#Expose
private List<Product> products = null;
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
-----------------------------------com.example.Product.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Product {
#SerializedName("id")
#Expose
private int id;
#SerializedName("pic")
#Expose
private String pic;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
If you want the list of pics within the products node, then you can get the entire JSON into a JSONObject, and iterate over the inner JSONArray
String str = "{\n" +
"\"pic\":\"1.jpg\",\n" +
"\"products\":[\n" +
"{\n" +
"\"id\":1,\n" +
"\"pic\":\"4.jpg\"\n" +
"}\n" +
"]\n" +
"\n" +
"}";
ArrayList<String> list = new ArrayList<>();
try {
JSONObject root = new JSONObject(str);
JSONArray products = root.getJSONArray("products");
for (int i = 0; i <= products.length(); i++) {
String value = ((JSONObject) products.get(i)).getString("pic");
list.add(value);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "onCreate: " + list);
I have a small class with some data, called MyData:
public class MyData {
public String name = "";
public String nameonly = "";
public int id = 0;
public double earn = 0;
public double paid = 0;
....
public MyData(String name, String nameonly, int id) {
this.name = name;
this.nameonly = nameonly;
this.id = id;
}
}
Then I have a class with arrays of this class for specific type of people called AllMyData:
public class AllMyData {
public ArrayList<MyData> cli = new ArrayList<>();
public ArrayList<MyData> sub = new ArrayList<>();
public ArrayList<MyData> emp = new ArrayList<>();
public ArrayList<MyData> exp = new ArrayList<>();
public ArrayList<MyData> oex = new ArrayList<>();
public ArrayList<MyData> bin = new ArrayList<>();
public ArrayList<MyData> ven = new ArrayList<>();
....
}
in main class I need to add new items to specific array (if id does not exists) where I have a string representative of AllMyData array
public AllMyData elems = new AllMyData();
public void initArray(int id, String name, String tip) {
//this is an example just for "cli" element and "cli" is in String tip
if (!checkForId(elems.cli, id)) {
MyData element = new MyData(name, name, id);
elems.cli.add(element);
}
}
private boolean checkForId(ArrayList<MyData> a, int id) {
for (MyData e : a) {
if (e.id == id) return true;
}
return false;
}
Then I need just a call, for example:
initArray(5, "Test", "emp");
and would like to avoid switch statement and to repeat code for every single type. In this call, "emp" would be element elems.emp
Is there a way to access elems member with a string name instead of creating switch statement?
Create a map of lists in AllMyData instead.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
AllMyData data = new AllMyData();
data.add("foo", new MyData("Hello World", "", 1));
data.add("cli", Arrays.asList(new MyData("BASH", "", 2), new MyData("SHELL", "", 3)));
System.out.println(data);
}
}
AllMyData [map={cli=[MyData [name=BASH, nameonly=, id=2, earn=0.0, paid=0.0], MyData [name=SHELL, nameonly=, id=3, earn=0.0, paid=0.0]], sub=[], oex=[], bin=[], foo=[MyData [name=Hello World, nameonly=, id=1, earn=0.0, paid=0.0]], emp=[], exp=[], ven=[]}]
import java.util.*;
public class AllMyData {
private Map<String, List<MyData>> map;
public AllMyData() {
map = new HashMap<String, List<MyData>>();
map.put("cli", new ArrayList<>());
map.put("sub", new ArrayList<>());
map.put("emp", new ArrayList<>());
map.put("exp", new ArrayList<>());
map.put("oex", new ArrayList<>());
map.put("bin", new ArrayList<>());
map.put("ven", new ArrayList<>());
}
public void add(String key, List<MyData> data) {
List<MyData> list = get(key);
if (list == null) {
map.put(key, data);
} else {
list.addAll(data);
map.put(key, list);
}
}
public void add(String key, MyData data) {
List<MyData> list = get(key);
if (list == null) {
list = new ArrayList<>();
}
list.add(data);
map.put(key, list);
}
public List<MyData> get(String key) {
return map.get(key);
}
#Override
public String toString() {
return String.format("AllMyData [map=%s]", map);
}
}
public class MyData {
public String name = "";
public String nameonly = "";
public int id = 0;
public double earn = 0;
public double paid = 0;
public MyData(String name, String nameonly, int id) {
this.name = name;
this.nameonly = nameonly;
this.id = id;
}
#Override
public String toString() {
return String.format("MyData [name=%s, nameonly=%s, id=%s, earn=%s, paid=%s]", name, nameonly, id, earn, paid);
}
}
Consider the use of a Map from String to ArrayList.
It would look like this:
Map> allMyData = new HashMap<>();
{
"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 String, received from HTTP request:
[
{
"id":15,
"title":"1",
"description":"desc",
"user_id":152
},
{
"id":18,
"title":"2",
"description":"desc",
"user_id":152
},
{
"id":19,
"title":"tab3",
"description":"zadanka",
"user_id":152
}
]
How to convert it into an ArrayList of Objects?
Using Gson
Gson gson = new Gson();
ArrayList<Object> listFromGson = gson.fromJson("json string",
new TypeToken<ArrayList<Object>>() {}.getType());
Using Jackson
ObjectMapper mapper = new ObjectMapper();
ArrayList<Object> listFromJackson = mapper.readValue("json string",
new TypeReference<ArrayList<Object>>(){});
If you could define a pojo as
public class Example {
private Integer id;
private String title;
private String description;
private Integer userId;
// setters / getters
}
Then
ArrayList<Example> listFromGson = gson.fromJson("json string",
new TypeToken<ArrayList<Example>>() {}.getType());
ArrayList<Example> listFromJackson = mapper.readValue("json string",
new TypeReference<ArrayList<Example>>(){});
Also, you should prefer using List instead of ArrayList.
You need to declare a pojo
class Data{
String id;
String title;
String description;
String userId;
//Generate setter an getter
}
The iterate over json like following:
JSONArray jsonArr = new JSONArray("[your JSON Stirng]");
List<Data> dataList = new ArrayList<Data>();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Data data = new Data();
data.setId(jsonObj.getString("id"));
data.setTitle(jsonObj.getString("title"));
data.setDescription(jsonObj.getString("description"));
data.setUserId(jsonObj.getString("user_id"));
dataList.add(data);
}
You also need json jar. You can download from here
If you are using RestApi then use the annotation #RequestBody with your pojo class.
#RequestMapping(value="/your api name", method=RequestMethod.POST)
public ResponseData createUser(#RequestBody MyPojo myPojo){
System.out.println("Creating User "+myPojo.toString());
//Here you will able to access your request data from myPojo object
}
Make your pojo class:
public class MyPojo
{
private Data[] data;
public Data[] getData ()
{
return data;
}
public void setData (Data[] data)
{
this.data = data;
}
#Override
public String toString()
{
return "ClassPojo [data = "+data+"]";
}
}
public class Data
{
private String id;
private String title;
private String description;
private String user_id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getUser_id ()
{
return user_id;
}
public void setUser_id (String user_id)
{
this.user_id = user_id;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+", title = "+title+", description = "+description+", user_id = "+user_id+"]";
}
}
In addition to #Sudhir, I would recommend to use Gson
Gson gson = new GsonBuilder().create();
Data p = gson.fromJson(jsonString, Data.class);
// Or to array.
Data[] data = gson.fromJson(jsonString, Data[].class);
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);
}
}