This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
i have problem to parse my json data,
this is my json data :
{"data":
[
{"ean": "222222","itemname": "","location": "001010202,001010201","po":[
{"ponumber": 1,"qty": 22
},
{"ponumber": 2,"qty": 33
}
]
},
{
"ean": "11112222",
"itemname": "เหงือก",
"location": "001010601",
"po": [
{
"ponumber": 1,
"qty": 7
}
]
},
{
"ean": "22223333",
"itemname": "Crystal Water",
"location": "001010410,001010401",
"po": [
{
"ponumber": 3,
"qty": 13
}
]
}
]}
i want to show the output like :
thank you
this is my java code to parsing json data and show to listview :
void parseJsonData(String jsonString) throws JSONException {
String data = "";
String data2 = null;
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname +"\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++ ) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2 = "\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n";
list.add(data+data2);
System.err.println(data+data2);
}
}
ArrayAdapter<String> LVarray;
LVarray = new ArrayAdapter<String>(ListActivity.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(LVarray);
}
this is screen shot the output:
1.You can use StringBuilder to save the data2(po List).
2.In the inner for loop ,you can use append method to add it in it .
3.Get the length of StringBuilder .Then remove the saved data2.
4.Then you can save again .
Edit
public void parseJsonData(String jsonString) throws JSONException {
String data = "";
StringBuilder data2 = new StringBuilder();
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname + "\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2.append("\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n");
list.add(data + data2);
}
System.err.println(data + data2);
int sb_length = data2.length();
data2.delete(0, sb_length);
}
}
this also can help
try {
//Get root array
JSONArray data_array = jsonObject.getJSONArray("data");
for (int i=0;i<data_array.length();i++){
JSONObject jsonObject1 = array.getJSONObject(i);
String ean = jsonObject1.optString("ean");
String itemname = jsonObject1.optString("itemname");
String location = jsonObject1.optString("location");
JSONArray child_Array = jsonObject1.getJSONArray("po");
for (int j=0;j<childArray.length();j++){
JSONObject childJosnObject = array.getJSONObject(i);
String ponumber = jsonObject1.optString("ponumber");
String qty = jsonObject1.optString("qty");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You have to try like this, it will help you
JsonParseModel jsonParseModel = new Gson().fromJson(jsonString,JsonParseModel.class);
public class JsonParseModel {
private ArrayList<DataClass> data;
public ArrayList<DataClass> getData() {
return data;
}
public void setData(ArrayList<DataClass> data) {
this.data = data;
}
public class DataClass{
private String ean,itemname,location;
private ArrayList<PoData> po;
public String getEan() {
return ean;
}
public void setEan(String ean) {
this.ean = ean;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public ArrayList<PoData> getPo() {
return po;
}
public void setPo(ArrayList<PoData> po) {
this.po = po;
}
public class PoData{
private int ponumber,qty;
public int getPonumber() {
return ponumber;
}
public void setPonumber(int ponumber) {
this.ponumber = ponumber;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
}
}
private void parseJsondata(String response) {
try {
// response
JSONObject jsonObject = new JSONObject(response);
// get data from JSONArray
JSONArray data = jsonObject.getJSONArray("data");
// for loop to your JSONArray's Strings
for (int i = 0; i < data.length(); i++) {
// get JSONObject from i
JSONObject jo = data.getJSONObject(i);
// get string
String ean = jo.getString("ean");
String itemname = jo.getString("itemname");
String location = jo.getString("location");
JSONArray jA = jo.getJSONArray("po");
for (int j = 0; j < jA.length(); j++) {
// get JSONObject by jO
JSONObject jO = jA.getJSONObject(i);
// get string
String ponumber = jO.getString("ponumber");
String qty = jO.getString("qty");
}
}
//Log response
Log.e("response:", response);
} catch (JSONException e) {
e.printStackTrace();
}
}
Related
So I am beginning programming Java Android and I'm trying to parse a JSON string that I created. So, I want to parse it to a ListView and I need people to help me.
My experimental JSON file:
[
{
"HoTen":" Nguy\u1ec5n V\u0103n A",
"NamSinh":1999,
"DiaChi":"H\u00e0 N\u1ed9i"
},
{+},
{+},
{+},
{+},
{+},
{+},
{+},
{+}
]
My code but it not working:
protected void onPostExecute(String s) {
//Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
mangLV = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(s);
JSONObject jsonObject = new JSONObject(s);
for (int i =0;i<=jsonObject.length();i++)
{
JSONObject object = jsonArray.getJSONObject(i);
//HoTen.getString("HoTen");
String HoTen = object.getString("HoTen");
int NamSinh = object.getInt("NamSinh");
String DiaChi = object.getString("DiaChi");
}
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mangLV);
lvSinhVien.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
Hope this will help you
protected void onPostExecute(String s) {
//Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
ArrayList<String> mangLV = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
//HoTen.getString("HoTen");
String HoTen = object.getString("HoTen");
int NamSinh = object.getInt("NamSinh");
String DiaChi = object.getString("DiaChi");
String result = String.format("HoTen: %s, NamSinh: %s, DiaChi: %s",
HoTen, NamSinh, DiaChi);
mangLV.add(result);
}
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, mangLV);
lvSinhVien.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
It doesn't seem like you're using your JSONObject jsonObject = new JSONObject(s);. Your for should be for(int i = 0; i<=jsonArray.length();i++), thus making your jsonObject obsolete. Also, you're passing your adapter an empty list! You never add anything to your mangLV list.
Try out this code:
protected void onPostExecute(String s) {
//Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
mangLV = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(s);
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String HoTen = object.getString("HoTen");
int NamSinh = object.getInt("NamSinh");
String DiaChi = object.getString("DiaChi");
String result = "HoTen " + HoTen + " | NamSinh " + NamSinh + " | DiaChi " + DiaChi;
mangLV.add(result); //After fetching the values, add the objects to your list
}
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mangLV);
lvSinhVien.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
This should add to your ListView objects that look like this:
HoTen Nguy\u1ec5n V\u0103n A | NamSinh 1999 | DiaChi H\u00e0 N\u1ed9i
I have a Restaurant List Object and also have a Cuisine List Object in that Restaurant List. How to Loop to show all cuisine data (New American, Japanese, Asia).
public class RestaurantList {
#SerializedName("restaurant_id")
#Expose
private String restaurantId;
#SerializedName("restaurant_name")
#Expose
private String restaurantName;
#SerializedName("cuisine")
#Expose
private List<Cuisine> cuisine = null;
public List<Cuisine> getCuisine() {
return cuisine;
}
public void setCuisine(List<Cuisine> cuisine) {
this.cuisine = cuisine;
}
}
In Restaurant RVAdapter, onBindViewHolder();
List<RestaurantList> mRestaurantList;
List<Cuisine> cuisineList = restaurantList.getCuisine();
String strCuisine = "";
for (int i = 0; i < cuisineList.size(); i++) {
strCuisine.concat(cuisineList.get(i).getCuisineName());
strCuisine.concat(",");
Log.i("Cuisine", cuisineList.get(i).getCuisineName());
holder.tv_restaurant_cuisine.setText(" " + cuisineList.get(i).getCuisineName());
}
Json Array;
[
{...},
{
"restaurant_id": "41",
"restaurant_name": "Shwe Lar Food Restaurant",
"cuisine": [
{
"cuisine_name": "New American"
},
{
"cuisine_name": "Japanese"
},
{
"cuisine_name": "Asia"
}
],
}
]
Use Below Method to parse your data:
I remove last , after array and {...}
private void parseJson(String jsonDataResponse){
try
{
JSONArray jsonArray = new JSONArray(jsonDataResponse);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String restaurant_id = jsonObject1.optString("restaurant_id");
String restaurant_name = jsonObject1.optString("restaurant_name");
JSONArray jsonArray1 =jsonObject1.getJSONArray("cuisine");
System.out.println("restaurant_id="+restaurant_id);
System.out.println("restaurant_name="+restaurant_name);
for(int j=0;j<jsonArray1.length();j++)
{
JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
String cuisine_name = jsonObject2.optString("cuisine_name");
System.out.println("cuisine_name="+cuisine_name);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i =0; i < result.length(); i++){
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
System.out.println("Sentence is:: " + s);
System.out.println("Id is:: " + id);
System.out.println("text file is:: " + txtFile);
}
} catch (JSONException e) {
e.printStackTrace();
}
currently, the above code is able to print out all the records. However, I would like to change the system.out.println into return variables such as return ID, return txtFile, return sentence. How to do that?
Create an Object. use an arraylist to store your object and use it later.
public class myItem{
String sentence;
int id;
String txtfile;
public myItem(){
}
public String getSentence(){
return sentence;
}
public setSentence(String s){
this.sentence = sentence;
}
}
public void yourFunction(){
try {
ArrayList <myItem> myList = new ArrayList();
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i =0; i < result.length(); i++){
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
myItem newItem = new myItem();
newItem.setSentence(s);
myList.add(newItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I agree with what Zhi Kai said in the comment.
PS. I can't comment yet so I'm writing this as an answer.
Create a POJO and u se data structure. In your case you are using a for loop so I assume you need to return a list of values from your JSONArray.
Here's what you can do.
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
List<YourObject> yourObjectToReturn = new ArrayList<YourObject>();
for (int i = 0; i < result.length(); i++) {
YourObject yourObject = new YourObject();
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
yourObject.setId(id);
yourObject.setTxtFile(txtFile);
yourObject.setSentence(s);
yourObjectToReturn.add(yourObject);
}
return yourObjectToReturn;
} catch (JSONException e) {
e.printStackTrace();
}
Updated:
public class YourObject {
private String id;
private String txtFile;
private String sentence;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTxtFile() {
return txtFile;
}
public void setTxtFile(String txtFile) {
this.txtFile = txtFile;
}
public String getSentence() {
return sentence;
}
public void setSentence(String sentence) {
this.sentence = sentence;
}
}
public List<YourObject> returnObject(){
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
List<YourObject> yourObjectToReturn = new ArrayList<YourObject>();
for (int i = 0; i < result.length(); i++) {
YourObject yourObject = new YourObject();
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
yourObject.setId(id);
yourObject.setTxtFile(txtFile);
yourObject.setSentence(s);
yourObjectToReturn.add(yourObject);
}
return yourObjectToReturn;
} catch (JSONException e) {
e.printStackTrace();
}
}
I have a JSON data in the following format,
[
{
"name": "France",
"date_time": "2015-05-17 19:59:00",
"dewpoint": "17",
"air_temp": "10.8"
},
{
"name": "England",
"date_time": "2015-05-17 19:58:48",
"dewpoint": "13",
"air_temp": "10.6"
},
{
"name": "Ireland",
"date_time": "2015-05-17 19:58:50",
"dewpoint": "15",
"air_temp": "11.1"
}
]
I have a Google map set up already for the Android app, so i have a pass the name value between two activity(GoogleMaps.java & WeatherInfo.java), now when i click a point in Google Map, it will pass the name to WeatherInfo.java, i want get the weather data for that name.
for example: i click France point in the map, The WeatherInfo.class will get the name is "France" and print out the "date_time, dewpoint, air_temp" for that point.
My question is how can i get the Json data parsed only for the point i clicked in the map? Can anyone look at the for loop in my WeatherInfo.java class?
WeatherInfo.java
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString(TAG_NAME);
String date_time = c.getString(TAG_DATE);
String temp = c.getString(TAG_TEMP);
String dewpoint = c.getString(TAG_DEWPOINT);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
contact.put(TAG_DATE, date_time);
contact.put(TAG_TEMP, temp);
contact.put(TAG_DEWPOINT, dewpoint);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
JSONArray array = (JSONArray)new JSONTokener(jsonStr).nextValue();
for(int i = 0; i<array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
String name = jsonObject.getString("name");
String date = jsonObject.getString("date_time");
...
}
Or
JSONArray array = (JSONArray)new JSONTokener(jsonStr).nextValue();
for(int i = 0; i<array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
City city = new City();
city.name = jsonObject.getString("name");
...
}
You could use Jackson json parser as follows:-
you will need a value object for the point data.
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Point {
private final String name;
private final String dateTime;
private final int dewpoint;
private final double airTemp;
#JsonCreator
public Point(#JsonProperty("name") final String name, #JsonProperty("date_time") final String dateTime, #JsonProperty("dewpoint") final int dewpoint, #JsonProperty("air_temp") final double airTemp) {
this.name = name;
this.dateTime = dateTime;
this.dewpoint = dewpoint;
this.airTemp = airTemp;
}
public String getName() {
return name;
}
public String getDateTime() {
return dateTime;
}
public int getDewpoint() {
return dewpoint;
}
public double getAirTemp() {
return airTemp;
}
}
Then this Jackson Object Mapper
// 2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
Point[] points = mapper.readValue(new File("points.json"), Point[].class);
for (Point point : points) {
System.out.println("" + point.getName());
System.out.println("" + point.getDateTime());
System.out.println("" + point.getDewpoint());
System.out.println("" + point.getAirTemp());
}
I'm fairly new to JSON parsing in Java but when I try and parse this JSON String & find out it's "ID", it repeats the same one twice.
[
{"id":"{ID1}","time":123},
{"id":"{ID2}","time":124}
]
This is my Java code:
// v = json string, c = "id"
String output = v.replace("[", "").replace("]", "");
JSONObject obj = new JSONObject(output);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0 ; i < obj.length(); i++){
System.out.println(obj.getString(c));
list.add(obj.getString(c));
}
return list.get(1);
it returns ID1 twice or more. Please help
Your JSON represents an array - so that's how you should parse it. You can then easily get the id property from each JSONObject within the array. For example:
import org.json.*;
public class Test {
public static void main(String[] args) throws JSONException {
String json =
"[{\"id\":\"{ID1}\",\"time\":123}, {\"id\":\"{ID2}\",\"time\":124}]";
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
System.out.println(o.getString("id"));
}
}
}
Output:
{ID1}
{ID2}
I fixed my code by using it as a JSONArray(Thanks #HotLicks)
JSONArray obj = new JSONArray(v);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0 ; i < obj.length(); i++){
Logger.WriteOutput(obj.getJSONObject(i).getString(c), Logger.LogLevel.Info);
}
Try this :
// This line is useless
// String output = v.replace("[", "").replace("]", "");
JSONArray arr = new JSONArray(output);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0 ; i < arr.length(); i++){
System.out.println(arr.getJSONObject(i).getString(c));
list.add(arr.getJSONObject(i).getString(c));
}
First create a java bean for your json (for example here):
public class Item {
#JsonProperty("id")
private String id;
#JsonProperty("time")
private Integer time;
public final String getId() {
return id;
}
public final void setId(String id) {
this.id = id;
}
public final Integer getTime() {
return time;
}
public final void setTime(Integer time) {
this.time = time;
}
}
If you are using Jackson Java JSON-processor, you can create a List from JSON-String this way:
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Item> items = objectMapper.readValue(
yourJSONString,
objectMapper.getTypeFactory().constructCollectionType(List.class, Item.class));
for (Item item : items) {
System.out.println(item.getId());
}
} catch (IOException e) {
e.printStackTrace();
}
use below code
String v = "[{\"id\":\"ID1\",\"time\":123},{\"id\":\"ID2\",\"time\":124}]";
String c = "id";
JSONArray obj = null;
try {
obj = new JSONArray(v);
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < obj.length(); i++) {
JSONObject j = (JSONObject) obj.get(i);
System.out.println(j.getString(c));
list.add(j.getString(c));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
note that i have slightly corrected the json structure too
before
[
{"id":"{ID1}","time":123},
{"id":"{ID2}","time":124}
]
after
[
{"id":"ID1","time":123},
{"id":"ID2","time":124}
]