I know that there are several questions posted on here with the same topic and error, but none of them indicate the same problem as mine, so I decided to post my question here, hoping that someone would help me point out the cause. Here's the code:
private void showEmployee(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONObject c = jsonObject.getJSONObject(Config.TAG_JSON_ARRAY);
Log.e("result",json);
if(c!=null) {
idwo=c.getString("id");
String notiangs = c.getString(Config.TAG_NOTIANG);
String alamats = c.getString(Config.TAG_ALAMAT);
String gardus = c.getString(Config.TAG_GARDU);
String penyulangs = c.getString(Config.TAG_PENYULANG);
String lats = c.getString(Config.TAG_GPSLAT);
String lons = c.getString(Config.TAG_GPSLON);
String kettings = c.getString(Config.TAG_JUMLAHKETTING);
notiang.setText(notiangs);
alamat.setText(alamats);
gardu.setText(gardus);
penyulang.setText(penyulangs);
lat.setText(lats);
lon.setText(lons);
ketting.setText(kettings);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
And this is the JSON response:
E/result: {"result":{"0":"3","id":"3","1":"abc1235gvv","no_tiang":"abc1235gvv","2":"JTM","jenis_tiang":"JTM","3":"","jumlah_ketting":"","4":"Mangkurayat","alamat":"Mangkurayat","5":"Cilawu","kecamatan":"Cilawu","6":"4555","kodepos":"4555","7":"Jawa Barat","provinsi":"Jawa Barat","8":"Kabupaten Garut","kota":"Kabupaten Garut","9":"adghc","penyulang":"adghc","10":"","gardu":"","11":"2017-05-01 08:49:49","tanggal":"2017-05-01 08:49:49","12":"107.88593833333334","lat":"107.88593833333334","13":"-7.249803333333333","lon":"-7.249803333333333"}}
So apparently there is a value for notiang, but I still got this warning in my logcat:
W/System.err: org.json.JSONException: No value for notiang
The error is so clear it says you cannot convert JSONArray to JSONObject then you need to change this line
JSONObject jsonObject = new JSONObject(json);
to this
JSONArray jsonArray = new JSONArray(json);
and then in a for loop get JSONObject of the index and do whatever you want
for determining your object whether is JSONArray or JSONObject you can do this
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
You are expecting a json object, while you are getting an array of json objects.
Change this Line
JSONObject c = jsonObject.getJSONObject(Config.TAG_JSON_ARRAY);
To
JSONArray peoples = null;
peoples = jsonObject .getJSONArray("Your Array Name/Tag);
The problem is your result have json array and your are trying it to convert to Json Object.
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
Log.e("result",json);
if(c!=null) {
idwo=c.getString("id");
String notiangs = c.getString(Config.TAG_NOTIANG);
String alamats = c.getString(Config.TAG_ALAMAT);
notiang.setText(notiangs);
alamat.setText(alamats);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONArray jArray= null;
jArray= jsonObject .getJSONArray("Key name);
}catch(Exception e){
}
Related
I am currently writing a program that pulls weather info from openweathermaps api. It returns a JSON string such as this:
{"coord":{"lon":-95.94,"lat":41.26},"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10n"}],"base":"stations","main": ...more json
I have this method below which writes the string to a .json and allows me to get the values from it.
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.get("weather"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}
The problem is it only allows me to get the outer values such as "coord" and "weather". So currently since I have System.out.println(Jobj.get("weather")); it will return [{"icon":"10n","description":"light rain","main":"Rain","id":500}] but I want to actually get the values that are inside of that like the description value and the main value. I haven't worked much with JSONs so there may be something obvious I am missing. Any ideas on how I would do this?
You can use JsonPath (https://github.com/json-path/JsonPath) to extract some json field/values directly.
var json = "{\"coord\":{\"lon\":\"-95.94\",\"lat\":\"41.26\"},\n" +
" \"weather\":[{\"id\":\"500\",\"main\":\"Rain\",\"description\":\"light\"}]}";
var main = JsonPath.read(json, "$.weather[0].main"); // Rain
you can use
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.getJSONObject("coord").get("lon");//here coord is json object
System.out.println(Jobj.getJSONArray("weather").get(0).get("description");//for array
or you can declare user defined class according to structure and convert code using GSON
Gson gson= new Gson();
MyWeatherClass weather= gson.fromJSON(Jobj .toString(),MyWeatherClass.class);
System.out.println(weather.getCoord());
From the json sample that you have provided it can be seen that the "weather" actually is an array of objects, so you will have to treat it as such in code to get individual objects from the array when converted to Jsonobject.
Try something like :
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject jobj = (JSONObject) obj;
JSONArray jobjWeatherArray = jobj.getJSONArray("weather")
for (int i = 0; i < jobjWeatherArray.length(); i++) {
JSONObject jobjWeather = jobjWeatherArray.getJSONObject(i);
System.out.println(jobjWeather.get("id"));
System.out.println(jobjWeather.get("main"));
System.out.println(jobjWeather.get("description"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}
So I'm kind of stuck. I'm experiencing with JSon and I'm trying to get all the total_price of different orders from a JSON file. I can read the file, but I'm having issue getting that specific information then sum it all up.
Here's the code I have so far.
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"/orders.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray orderList = (JSONArray) jsonObject.get("orders");
System.out.println("\norders");
Iterator<String> iterator = orderList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
obj = parser.parse(sCurrentLine);
JSONArray jsonArray = (JSONArray) obj;
for(obj : jsonArray){
JSONObject jsonObject = (JSONObject)obj;
JSONObject realTitle = (JSONObject)jsonObject.get("0");
String name = (String) realTitle.get("title");
}
} catch (Exception e) {
e.printStackTrace();
}
}
For the JSON file:
{
"orders":[
{
"id":4251070723,
"email":"heathcote_amya#gmail.com",
"closed_at":null,
"created_at":"2016-12-05T23:16:40-05:00",
"updated_at":"2016-12-05T23:16:40-05:00",
"number":137,
"note":null,
"token":"c460f260f4f38b8a2b1f78e6efd0140e",
"gateway":"",
"test":false,
"total_price":"179.04",
"default":true
},
{
"id":4251070787,
"email":"napoleon.batz#gmail.com",
"closed_at":null,
"created_at":"2016-12-05T23:16:40-05:00",
"updated_at":"2016-12-05T23:16:41-05:00",
"number":138,
"note":null,
"token":"54c4f1735cfec8f98ad16ae5e9a161cd",
"gateway":"",
"test":false,
"total_price":"14.62"
}
]
}
The error I get is for(obj : jsonArray) is causing me issue, but honestly, I don't think I'm even on the right path.
Thanks a lot for your help in advance!
Your code has obvious compile time errors. With in the for loop, you are again trying to do a get(0), which is incorrect.
I have refined the code.
Try this. Its giving proper result as below
The price data of each order --{4251070723=179.04, 4251070787=14.62}.
The total Price of all order --193.66
public static void main(String[] args) {
JSONParser parser = new JSONParser();
Map<String, String> priceData = new HashMap<>();
BigDecimal totalPrice = BigDecimal.ZERO;
String orderId = null;
String orderPrice = null;
try {
String sCurrentLine = null;
Object obj = parser.parse(new FileReader(
"orders.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray orderList = (JSONArray)(jsonObject.get("orders"));
System.out.println("Complete order list --"+orderList.toString());
for(Object singleOrder : orderList) {
JSONObject singleArrayData = (JSONObject) singleOrder;
orderId = singleArrayData.get("id").toString();
orderPrice = singleArrayData.get("total_price").toString();
priceData.put(orderId, orderPrice);
totalPrice = totalPrice.add(new BigDecimal(orderPrice));
}
System.out.println("The price data of each order --"+priceData.toString());
System.out.println("The total Price of all order --"+totalPrice);
} catch (Exception e) {
e.printStackTrace();
}
}
The problem that I'm facing right now is I simply want to set the string data from a json array in onPostExecute(). I skeemed through many tutorials on it, however, I am unable to set the Text that resides in the MainActivity. I've added the sample code below . I wonder if the data is wrong .
#SuppressWarnings("unchecked")
protected void onPostExecute(JSONObject jsonobject) {
try {
jsonarray = jsonobject.getJSONArray("grape");
outerjson = jsonarray;
String ids = jsonobject.optString("id");
String tpes = jsonobject.optString("type");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
String str = "";}
// Step 3.
map1 = new HashMap<String, String>();
// this is the last step 4.
try {
JSONArray jArray = new JSONArray(str);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = null;
json = jArray.getJSONObject(i);
map1.put("id", json.getString("id"));
map1.put("type", json.getString("type"));
}
result.setText(jsonarray.toString());
///set the json in here
}catch (JSONException e) {}
} catch (JSONException e) {}
progressDialog.dismiss();
}
Not enough information, but I will try:
Make your code cleaner by using a container entity: MyData data = gson.fromJson(jsonobject, MyData.class).
Do not ignore exceptions
Make sure you are calling result.setText(string); within a main UI thread
Follow these 3 steps and, find the error, you will.
Good morning.
I am trying to parse JSON data into a string but I think I'm doing something wrong: here is the section.
private void read_JSON()
{
String JSON;
JSONObject jso3 = new JSONObject(JSON);
for (int i=0; i < jso3.length(); i++)
{
try
{
String name = jso3.getString("Nombre");
String surname = jso3.getString("Apellidos");
String date = jso3.getString("Año_nacimiento");
String child_names = jso3.getString("Nombres_Hijos");
}catch (JSONException e)
{
e.printStackTrace();
}
}
jso3.toString(JSON);
}
I created the JSON within the MainActivity.java, it's not on a separate file.
Here is the code of the JSON creation:
private void create_JSON()
{
JSONObject jso = new JSONObject();
try {
jso.put("Nombre","Miguel");
jso.put("Apellidos", "Garcia");
jso.put("Año_nacimiento", 1990);
JSONArray jsa = new JSONArray();
jsa.put("Blur");
jsa.put("Clur");
jso.put("Nombres_Hijos", jsa);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jso.toString();
I have no doubts that the JSON is correctly created, I just need help in understanding how do I parse it and convert it into a String.
I would be very grateful if you could point out to me the flaws in my programming.
Mauro.
Try this..
Your response like below
{ ==> JSONObject
"Año_nacimiento": 1990, ==> String from JSONObject
"Nombres_Hijos": [ ==> JSONArray
"Blur", ==> Directly from JSONArray
"Clur"
],
"Apellidos": "Garcia",
"Nombre": "Miguel"
}
To parse the JSON use below code:
JSONObject jso3 = new JSONObject(output);
String name = jso3.getString("Nombre");
String surname = jso3.getString("Apellidos");
int date = jso3.getInt("Año_nacimiento");
JSONArray menuObject = jso3.getJSONArray("Nombres_Hijos");
for(int i=0;i<menuObject.length;i++){
System.out.println(menuObject.getString(i));
}
Use the following options while parsing JSON to avoid common error.
JSONObject jso3 = new JSONObject(output);
String name = jso3.optString("Nombre",""); // here default value is blank ("")
String surname = jso3.optString("Apellidos",null);// here default value is null
int date = jso3.getInt("Año_nacimiento",0); // here default value is ZERO (0)
JSONArray menuObject = jso3.getJSONArray("Nombres_Hijos");
for(int i=0;i<menuObject.length;i++){
System.out.println(menuObject.getString(i));
}
Using opt option you can set default return value. Event if that tag not available in JSON data you will get default value.
This works for me better than GSON lib.
Try this.
String apellidos = jso.getString("Apellidos");
System.out.println(apellidos);
int str2 = jso.getInt("Año_nacimiento");
System.out.println(str2);
String nombre = jso.getString("Nombre");
System.out.println(nombre);
JSONArray array = jso.getJSONArray("Nombres_Hijos");
for(int i = 0; i < array.length(); i++){
System.out.println(array.get(i));
}
First at all, you seem to ignore Strings created in read_JSON, but i assume you do this to avoid pasting here too much code.
Problem is this line:
String child_names = jso3.getString("Nombres_Hijos");
Because fields Nombres_Hijos is JsonArray, not String. To read it use:
JSONArray jsa = jso3.getJSONArray("Nombres_Hijos");
Now all depands what you need to do later with this data.
Easiest case would be:
String names = jsa.toString(); //["Blur","Clur"]
private void read_JSON(String json)
{
JSONObject jObject= new JSONObject(json);
JSONArray jso3= new JSONArray(jObject.getString("Nombres_Hijos"));
for (int i=0; i < jso3.length(); i++)
{
try
{
String name = jso3.getString("Nombre");
String surname = jso3.getString("Apellidos");
String date = jso3.getString("Año_nacimiento");
String child_names = jso3.getString("Nombres_Hijos");
}catch (JSONException e)
{
e.printStackTrace();
}
}
jso3.toString(JSON);
}
try{
String JSON ;
JSONObject jso3 = new JSONObject(JSON);
JSONArray menuObject = new JSONArray(jObject.getString("array_inside_json"));
for(int i=0;i<menuObject.length;i++){
name=jObject.getString("inside"));
}
}catch(Exception e){
}
refer this link for more info
i want show data with jsonarray
my code activity
params.add(new BasicNameValuePair("id_gadai", id_gadai));
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_GADAI_DETAIL, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Data Gadai Detail: ", json);
try {
JSONObject jObj = new JSONObject(json);
if(jObj != null){
nama_brg = jObj.getString(TAG_NAMA_BRG);
taksiran = jObj.getString(TAG_TAKSIRAN);
pinjaman = jObj.getString(TAG_PINJAMAN);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
my jsonarray from database
{"data_gadai_detail":[{"id_gadai":"3","nama_brg":"BERLIAN L FINE GOLD
BERSERTIFIKAT NO.SERI JS 006 DTM 24K BRT 10
GRAM","pinjaman":"2000000","taksiran":"4000000","tgl_bts_tebus":"05-May-2013","tgl_bts_lelang":"09-May-2013"}]}
show error :
Error JSONException: No Value For nama_brg
Need help for my problem. thks
Your JSON represents an object with one single field: data_gadai_detail:
{"data_gadai_detail": ...}
The value of this field is an array with a single element:
{"data_gadai_detail": [...]}
This single element is an object with several fields, one of them being nama_brg.
So your code should first get the field data_gadai_detail as an array, take the first element of this array as another JSON object, and finally get the String nama_brg in this object.
You have a JSONArray named "data_gadai_detail" as root, then you need to get the first JSONObject and then you can get the JSONStrings
try this:
JSONObject jObj = new JSONObject(json);
if(jObj != null){
nama_brg = jObj.getJSONArray("data_gadai_detail").getJSONObject(0).getString(TAG_NAMA_BRG);
taksiran = jObj.getJSONArray("data_gadai_detail").getJSONObject(0).getString(TAG_TAKSIRAN);
pinjaman = jObj.getJSONArray("data_gadai_detail").getJSONObject(0).getString(TAG_PINJAMAN);
}
try this one..
JSONObject jObj = new JSONObject(json);
JSONArray arr = jObj.getJSONArray("data_gadai_detail");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
nama_brg = c.getString(TAG_NAMA_BRG);
taksiran = c.getString(TAG_TAKSIRAN);
pinjaman = c.getString(TAG_PINJAMAN);
}