I'm having trouble retrieving the Id from a JSONObject and passing it to a String to record the Id of that players particular puzzle but on the line String idString = obj.getString("Id");
"I get org.json.JSONException: No value for Id"
I'm getting this information by calling to the server in this class which checks the username and password of the player.
import android.os.AsyncTask;
import android.text.format.Time;
import android.util.Log;
public class GetTodaysPuzzle implements OnRetrieveHttpData {
public String GetTodaysPuzzle(String mUserName, String mPassword)
{
RetrieveHTTPData GetTodayspuzzle = new RetrieveHTTPData(this);
return GetTodayspuzzle.GetResponseData("urlString" + mUserName + "&password=" + mPassword);
}
#Override
public void onRetrieveTaskCompleted(String httpData) {
Log.i("Server Response", httpData);
}
class GetTodaysPuzzleTask extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
// Get response from server
String json = GetTodaysPuzzle(params[0], params[1]);
// Check if a puzzle was returned
if (json.contains("The request is invalid"))
{
return false;
}
try
{
// Calculate today's date in order to set wordsearch date
Time today = new Time();
today.setToNow();
String formattedDate = Dates.ConvertUStoUK(today.year + "-"
+ (today.month + 1) + "-" + today.monthDay);
// Create wordsearch
WordSearch wordSearch = WordSearch.CreateWordSearch(json,
formattedDate);
if (wordSearch == null)
{
return false;
}
// Save wordsearch to collection
WordSearchDatabase.Add(wordSearch);
// WordSearchDatabase.Save();
return true;
}
catch (Exception e)
{
Log.e("GetTodaysPuzzleTask", e.getMessage());
return false;
}
}
}
}
And then stores all the information into JSONArrays in the Wordsearch class.
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class WordSearch {
public String Id;
public String Date;
public List<Word> Words;
public Letter[] Letters;
public final int NUM_OF_ROWS;
public final int NUM_OF_COLS;
public int Score = -1;
private boolean containsSolution = false;
public boolean canBeSubmitted = true;
private boolean complete = false;
private boolean submitted = false;
public static WordSearch CreateWordSearch(String json, String date)
{
List<Word> listOfWords = new ArrayList<Word>();
List<String> listOfRows = new ArrayList<String>();
try
{
// Create a JSON Object from JSON string
JSONObject obj = new JSONObject(json);
// Get Id
String idString = obj.getString("Id");
// GetWords & Puzzle as JSON Arrays
JSONArray wordsArray = obj.getJSONArray("Words");
JSONArray puzzleArray = obj.getJSONArray("Grid");
// Parse Words array
for (int i = 0; i < wordsArray.length(); i++)
{
String name = wordsArray.getString(i);
Word word = new Word(name);
listOfWords.add(word);
}
// Parse Puzzle
for (int k = 0; k < puzzleArray.length(); k++)
{
String puzzle = puzzleArray.getString(k);
listOfRows.add(puzzle);
}
// Create WordSearch
return new WordSearch(idString, date, listOfWords, listOfRows,
false);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
This is the first time I have used API servers and JSONObject's in Android so any help would be much appreciated. Thank you.
You are getting this error because your response JSON doesn't have "Id" as a key, It only has "Puzzle" as you can see:
{
"Puzzle": {
"Id": "8fb25209-863a-410b-a440-b5b57a903ee1",
"Words": ["CHATEAUX", ...],
"Grid": ["TLIOFSHTRC", ...]
}
}
You need to first get the "Puzzle" object first and then you can get the "Id" from that object.
JSONObject obj = new JSONObject(json);
JSONObject puzzle = obj.getJSONObject("Puzzle");
String idString = puzzle.getString("Id");
....
Id is in the puzzle element so it should be
JSONObject obj = new JSONObject(json);
//get puzzle object
JSONObject puzzle = obj.getJSONObject("Puzzle");
// Get Id
String idString = puzzle.getString("Id");
// GetWords & Puzzle as JSON Arrays
JSONArray wordsArray = puzzle.getJSONArray("Words");
JSONArray puzzleArray = puzzle.getJSONArray("Grid");
Related
Hi i am trying to iterate through a json string that looks like this:
{
"vendor":[
{
"vendor_name":"Tapan Moharana",
"vendor_description":"",
"vendor_slug":"tapan",
"vendor_logo":null,
"contact_number":null
}
],
"products":
{
"25":
{
"name":"Massage",
"price":"5000.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/2\/9\/29660571-beauty-spa-woman-portrait-beautiful-girl-touching-her-face.jpg"
},
"26":
{
"name":"Chicken Chilly",
"price":"234.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/c\/h\/cheicken.jpg"
},
"27":
{
"name":"Chicken Biryani",
"price":"500.0000",
"image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/placeholder\/default\/image_1.jpg"
}
}
}
here is a better view of the json string:
I am iterating through the vendor array of this json string using this code:
JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
}
but I dont know how to get data from the "products" object please help me how do i set my json objects to iterate through "products"
when i try to change the format of the array so that both products and vendor are a separate json array i still get the above json format..
this is what i am doing
$resp_array['vendor'] = $info;
$resp_array['products'] = $vendorProductsInfo;
$resp_array = json_encode($resp_array);
print_r($resp_array);
please help me with this
MODIFIED QUESTION:
I have modified my web response like this:
[{"entity_id":24,"product_name":"Burger","product_image_url":"\/b\/u\/burger_large.jpg","price":"234.0000","category_id":59},{"entity_id":27,"product_name":"Chicken Biryani","product_image_url":"\/b\/i\/biryani.jpg","price":"500.0000","category_id":59},{"entity_id":31,"product_name":"Pizza","product_image_url":"\/p\/i\/pizza_png7143_1.png","price":"125.0000","category_id":59}]
and the code:
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
JSONObject jsonData = children.getJSONObject(i);
System.out.print(jsonData.getString("vendor_name") + "<----");
// String vendorThumbNailURL=jsonData.getString("")
//jvendorImageURL.setImageUrl(local, mImageLoader);
vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
jvendorName.setText(jsonData.getString("vendor_name"));
jvendorAbout.setText(jsonData.getString("vendor_description"));
jvendorContact.setText(jsonData.getString("contact_number"));
System.out.print(jsonData.getString("products") + "<----");
}
JSONObject jsono1 = new JSONObject(response);
JSONArray childrenProducts = jsono1.getJSONArray("products");
for(int i=0;i<childrenProducts.length();i++){
JSONObject jsonData = childrenProducts.getJSONObject(i);
System.out.print(jsonData.getString("name") + "<----dd");
}
but still the products part is not working... please help
Here is the working solution: Using GOOGLE GSON (Open source jar)
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonToJava {
public static void main(String[] args) throws IOException {
try{
String json = "<YOUR_JSON>";
Gson gson = new GsonBuilder().create();
VendorInfo vInfo = gson.fromJson(json, VendorInfo.class);
System.out.println(vInfo.getVendorName());
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Create classes for Vendor and Product
public class Vendor {
public String vendor_name;
public String vendor_description;
public String vendor_slug;
public String vendor_logo;
public String contact_number;
public String getName() {
return vendor_name;
}
}
public class Product {
public String name;
public long price;
public String image;
public String getName() {
return name;
}
}
VendorInfo is the JSON object form:
import java.util.Map;
public class VendorInfo {
public Vendor[] vendor;
public Map<Integer, Product> products;
public String getVendorName() {
return vendor[0].getName();
}
public Product getProduct() {
System.out.println(products.size());
return products.get(25);
}
}
You can add your getters for Vendor, Product and VendorInfo. You are done! You will get all the data.
Output of JsonToJava:
Tapan Moharana
To get your products data , you need to use Iterator
JSONObject jProducts = jsonObject
.optJSONObject("products");
try {
if (jProducts
.length() > 0) {
Iterator<String> p_keys = jProducts
.keys();
while (p_keys
.hasNext()) {
String keyProduct = p_keys
.next();
JSONObject jP = jProducts
.optJSONObject(keyProduct);
if (jP != null) {
Log.e("Products",
jP.toString());
}
}
}
} catch (Exception e) { // TODO:
// handle
// exception
}
you can try with this
JSONObject jsono = null;
try {
jsono = new JSONObject(response);
JSONObject productObject = jsono.getJSONObject("products");
Iterator<String> keys = productObject.keys();
while (keys.hasNext())
{
// get the key
String key = keys.next();
// get the value
JSONObject value = productObject.getJSONObject(key);
//get seprate objects
String name = value.getString("name");
String image = value.getString("image");
Log.i(TAG,name+"-"+image);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Try this :
JSONObject productObject = jsono.getJSONObject("products");
JSONObject json_25 = productObject getJSONObject("25");
String name_25= json_25.getString("name");
String price_25= json_25.getString("price");
String image_25= json_25.getString("image");
JSONObject json_26 = productObject getJSONObject("26");
String name_26= json_26.getString("name");
String price_26= json_26.getString("price");
String image_26= json_26.getString("image");
JSONObject json_27 = productObject getJSONObject("27");
String name_27= json_27.getString("name");
String price_27= json_27.getString("price");
String image_27= json_27.getString("image");
I'm trying to read JSON file in Java (I'm starting with JSON).
The JSON file:
[
{
"idProducto":1,
"Nombre":"Coca Cola",
"Precio":0.9,
"Cantidad":19
},
{
"idProducto":2,
"Nombre":"Coca Cola Zero",
"Precio":0.6,
"Cantidad":19
},
[....]
]
I tried the following:
ArrayList<Dispensador> Productos = new ArrayList<Dispensador>();
FileReader reader = new FileReader(new File("productos.json"));
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
JSONObject object = (JSONObject) jsonArray.get(0);
Long idProducto = (Long) object.get("idProducto");
JSONArray nombres = object.getJSONArray("idProducto");
Iterator i = jsonArray.iterator();
while (i.hasNext()) {
String nombre = (String) object.get("Nombre");
Double precio = (Double) object.get("Precio");
BigDecimal precioB = new BigDecimal(precio);
Long cantidad = (Long) object.get("Cantidad");
int cantidadB = toIntExact(cantidad);
System.out.println(nombre);
Productos.add(new Dispensador(nombre, precioB, cantidadB));
}
But enters into loop. Also I tried with a for loop, but no luck.
Thanks!
You can use gson library
You can use Maven or jar file: http://mvnrepository.com/artifact/com.google.code.gson/gson
package com.test;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class AppJsonTest {
public static void main(String[] args) {
List<DataObject> objList = new ArrayList<DataObject>();
objList.add(new DataObject(1, "Coca Cola", 0.9, 19));
objList.add(new DataObject(2, "Coca Cola Zero", 0.6, 19));
// Convert the object to a JSON string
String json = new Gson().toJson(objList);
System.out.println(json);
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<DataObject>>() {
}.getType();
List<DataObject> inpList = new Gson().fromJson(json, type);
for (int i = 0; i < inpList.size(); i++) {
DataObject x = inpList.get(i);
System.out.println(x.toString());
}
}
}
class DataObject {
int idProducto;
String Nombre;
Double Precio;
int Cantidad;
public DataObject(int idProducto, String nombre, Double precio, int cantidad) {
this.idProducto = idProducto;
Nombre = nombre;
Precio = precio;
Cantidad = cantidad;
}
public int getIdProducto() {
return idProducto;
}
public void setIdProducto(int idProducto) {
this.idProducto = idProducto;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
Nombre = nombre;
}
public Double getPrecio() {
return Precio;
}
public void setPrecio(Double precio) {
Precio = precio;
}
public int getCantidad() {
return Cantidad;
}
public void setCantidad(int cantidad) {
Cantidad = cantidad;
}
#Override
public String toString() {
return "DataObject [idProducto=" + idProducto + ", Nombre=" + Nombre + ", Precio=" + Precio + ", Cantidad=" + Cantidad + "]";
}
}
Use gson library to read and write json:
try {
JsonReader reader = new JsonReader(new FileReader("json_file_path.json"));
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("idProducto")) {
System.out.println(reader.nextInt());
} else if (name.equals("Nombre")) {
System.out.println(reader.nextString());
} else if (name.equals("Precio")) {
System.out.println(reader.nextDouble());
} else if (name.equals("Cantidad")) {
System.out.println(reader.nextInt());
} else {
reader.skipValue();
}
}
reader.endObject();
}
reader.endArray();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
download http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip
You are testing whether the iterator has a next element with i.hasNext(). But you don't consume (or retrieve) this next element by i.next() which is typically in the first statement of the looped block. Therefore i.hasNext() will return true forever.
EDIT: You probably want to set object to i.next() because in your code snippet it always remains at the 0's element you assigned before the loop.
There are many open source libraries, present to parse json to object or just to read and write json values. If you want to read and write json then you can use org.json library.
Use org.json library to parse it and create JsonObject :-
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values :-
String id = jsonObj.getString("pageInfo");
You can see complete example here :-
How to parse Json in java
If you want to parse your json to particular POJO and then use that pojo to get values, then use jackson-databind library, this will parse your json to POJO class :-
ObjectMapper mapper = new ObjectMapper();
book = mapper.readValue(json, Book.class);
You can see complete example here, How to parse json in java
Scanner input = new Scanner(System.in);
JSONArray finaljson = new JSONArray();
for (int j = 0; j < 2; j++) {
System.out.println("Enter Version Name");
String vName = input.next();
System.out.println("Enter Version Key");
;
String vKey = input.next();
JSONObject root = new JSONObject();
if (!root.has("versionName")) {
root.put("versionName", vName);
root.put("versionKey", vKey);
}
JSONArray issue = new JSONArray();
System.out.println("Enter Epic Name");
String epicName = input.next();
System.out.println("Enter Epic Key");
String epicKey = input.next();
JSONObject epicData = new JSONObject();
epicData.put("epickKey", epicKey);
epicData.put("epickName", epicName);
issue.put(epicData);
root.put("issue", issue);
finaljson.put(root);
}
System.out.println("JSON DATA" + finaljson.toString());
Hey Making a JSON,as from the code if user will enter versionname is multiple time that it should not add in root jsonobject. so how to restrict it.
[
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e1",
"epickKey": "ekey1"
}
],
"versionName": "v1"
},
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e2",
"epickKey": "eky2"
}
],
"versionName": "v1"
}
]
but want
[
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e1",
"epickKey": "eky1"
},
{
"epickName": "e2",
"epickKey": "eky2"
}
],
"versionName": "v1"
}
]
can you help me how to make this type of dynamic json data
If I understand correctly, you want the output to be like the second JSON array in your question. Changing where you loop should do the trick:
Scanner input = new Scanner(System.in);
JSONArray finaljson = new JSONArray();
System.out.println("Enter Version Name");
String vName = input.next();
System.out.println("Enter Version Key");;
String vKey = input.next();
JSONObject root = new JSONObject();
if (!root.has("versionName")) {
root.put("versionName", vName);
root.put("versionKey", vKey);
}
JSONArray issue = new JSONArray();
for (int j = 0; j < 2; j++) {
System.out.println("Enter Epic Name");
String epicName = input.next();
System.out.println("Enter Epic Key");
String epicKey = input.next();
JSONObject epicData = new JSONObject();
epicData.put("epickKey", epicKey);
epicData.put("epickName", epicName);
issue.put(epicData);
}
root.put("issue", issue);
finaljson.put(root);
System.out.println("JSON DATA" + finaljson.toString());
I tested with the input you have. Here is the formatted JSON output:
[
{
"issue": [
{
"epickKey": "eky1",
"epickName": "e1"
},
{
"epickKey": "eky2",
"epickName": "e2"
}
],
"versionName": "vkey1",
"versionKey": "v1"
}
]
Read in your json using Gson:
Define Pojos for your Json Objects:
public class Epic {
String versionKey, versionName;
Issue issue;
}
public class Issue{
String epicName, epicKey;
}
Load Pojos from json using Gson
// Create gson object
Gson gson = new GsonBuilder().create();
// Load your json objects:
BufferedReader br = new BufferedReader(new FileReader("file.json"));
List<Epic> epics = gson.fromJson(br, new TypeToken<ArrayList<Epic>>() {}.getType());
Create the class structure you want for your "multi-issue-epics":
// This will be used to store in the format you want
public class MultiIssueEpic{
public String versionKey, versionName;
public Set<Issue> issueSet;
public MultiIssueEpic(Epic epic){
this.versionName = epic.versionName;
this.versionKey = epic.versionKey;
this.issueSet = new HashSet<>();
this.issueSet.add(epic.issue);
}
}
Build the MultiIssueEpic up from your List<Epic>:
Map<String, MultiIssueEpic> epicMap = new HashMap<>();
for(Epic epic : epics){
if(epicMap.contains(epic.versionName)){
// Add issue to existing MultiIssueEpic
epicMap.get(epic.versionName).issueSet.add(epic.issue);
} else{
// Add new MultiIssueEpic
epicMap.put(epic.versionName, new MultiIssueEpic(epic));
}
}
// Here is your list of MultiIssueEpics:
List<MultiIssueEpic> multiIssueEpics = new ArrayList<>(epicMap.values());
I change your code and I add two other class. One named Data for (versionKey, nameKey), the second one Epic for (epickName,epickKey)
and to generate Json, I use Gson lib.
This code :
Epic Class:
public class Epic {
private String epicName;
private String epicKey;
public Epic() {
}
public Epic(String epicName, String epicKey) {
this.epicName = epicName;
this.epicKey = epicKey;
}
public String getEpicName() {
return epicName;
}
public void setEpicName(String epicName) {
this.epicName = epicName;
}
public String getEpicKey() {
return epicKey;
}
public void setEpicKey(String epicKey) {
this.epicKey = epicKey;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Epic [epicName=");
builder.append(epicName);
builder.append(", epicKey=");
builder.append(epicKey);
builder.append("]");
return builder.toString();
}
}
Data Class :
import java.util.List;
public class Data {
private String versionName;
private String versionKey;
private List<Epic> epics;
public Data() {
}
public Data(String versionName, String versionKey, List<Epic> epics) {
this.versionName = versionName;
this.versionKey = versionKey;
this.epics = epics;
}
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public String getVersionKey() {
return versionKey;
}
public void setVersionKey(String versionKey) {
this.versionKey = versionKey;
}
public List<Epic> getEpics() {
return epics;
}
public void setEpics(List<Epic> epics) {
this.epics = epics;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((versionKey == null) ? 0 : versionKey.hashCode());
result = prime * result
+ ((versionName == null) ? 0 : versionName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Data other = (Data) obj;
if (versionKey == null) {
if (other.versionKey != null)
return false;
} else if (!versionKey.equals(other.versionKey))
return false;
if (versionName == null) {
if (other.versionName != null)
return false;
} else if (!versionName.equals(other.versionName))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Data [versionName=");
builder.append(versionName);
builder.append(", versionKey=");
builder.append(versionKey);
builder.append(", epics=");
builder.append(epics);
builder.append("]");
return builder.toString();
}
}
Main Class:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Data> datas = new ArrayList<Data>();
boolean add = false;
for (int j = 0; j < 2; j++) {
add = false;
Data data = new Data();
System.out.println("Enter Version Name");
data.setVersionName(input.next());
System.out.println("Enter Version Key");
data.setVersionKey(input.next());
Epic epic = new Epic();
System.out.println("Enter Epic Name");
epic.setEpicName(input.next());
System.out.println("Enter Epic Key");
epic.setEpicKey(input.next());
List<Epic> epics = new ArrayList<Epic>();
if(datas.isEmpty()){
epics.add(epic);
data.setEpics(epics);
datas.add(data);
}else{
for(Data d:datas){
if(d.equals(data)){
d.getEpics().add(epic);
add=true;
}
}
if(!add){
epics.add(epic);
data.setEpics(epics);
datas.add(data);
}
}
}
//Gson gson = new GsonBuilder().setPrettyPrinting().create();
//System.out.println(gson.toJson(datas));
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(datas);
System.out.println(jsonArray.toString());
}
}
PS: Url to download Gson API
Edit
I made a change in the Main Class to use json-lib-2.4-jdk15.jar
Take a look at this URL:
json-lib
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}
]