I'm trying to read JSON but I got below error.
2019-08-27 13:12:43.352 27379-27379/com.test W/System.err: org.json.JSONException: Value transcript of type java.lang.String cannot be converted to JSONObject
JSON
{"transcript":{"text":[{"content":"Flood!","dur":"1.76","start":"2.28"},{"content":"Listen up, there’s a flood coming!","dur":"2.24","start":"4.52"},{"content":"Oy lads, flood!","dur":"1.92","start":"7.88"},{"content":"There’s a flood –","dur":"1.24","start":"10.72"},{"content":"Maurice, they’re not listening.","dur":"1.84","start":"13.96"},{"content":"We’ve got to give them\na good old-fashioned fish slappin’.","dur":"2.8","start":"15.96"},{"content":"Fish Slap!","dur":"1.04","start":"20.52"},{"content":"Fish Slap!","dur":"1","start":"22.32"},{"content":"Fish Slap!","dur":"1.2","start":"24.12"},{"content":"Double Fish Slap!","dur":"1.24","start":"25.84"},{"content":"See, guys? Flood’s here.","dur":"1.56","start":"27.84"},{"content":"Tub Rider!","dur":"2.48","start":"31.56"},{"content":"SEASON 1\nTHE FLOOD","dur":"1","start":"35.32"},{"content":"Because I’m in a tub!","dur":"1.04","start":"36.48"},{"content":"PREPARE TO BATTLE ON A BOAT","dur":"1.48","start":"37.68"}]}}
Code
try {
JSONObject jsonObject = new JSONObject("transcript");
JSONArray jsonArray = new JSONArray("text");
Log.w("aaa",String.valueOf(jsonArray.getJSONObject(0).get("content")));
} catch (JSONException e) {
e.printStackTrace();
}
Put your json into a String and then try to parse it :
String json = "{\"transcript\":{\"text\":[{\"con ...}";
try {
JSONObject jsonObject = new JSONObject(json);
JSONObject jsonObject = new JSONObject("transcript");
JSONArray jsonArray = new JSONArray("text");
Log.w("aaa",String.valueOf(jsonArray.getJSONObject(0).get("content")));
} catch (JSONException e) {
e.printStackTrace();
}
Remember to escape your double quotes with backslash
From your question and code you've provided, I understand that you are new and unfamiliar with the JSON APIs in Android. For this, I suggest you read the official documentation and get yourself familiar with org.json API (JSONObject, JSONArray):
https://developer.android.com/reference/org/json/JSONObject
https://developer.android.com/reference/org/json/JSONArray
After, you may want to practice and follow some tutorials on serialization/deserialization of JSON in Android using the org.json API. Here is a fairly complete tutorial I just found for you on the net (just an example, there are literally hundreds out there):
https://www.javacodegeeks.com/2013/10/android-json-tutorial-create-and-parse-json-data.html
String response = "{"transcript":{"text":[{"content":"Flood!","dur":"1.76","start":"2.28"},{"content":"Listen up, there’s a flood coming!","dur":"2.24","start":"4.52"},{"content":"Oy lads, flood!","dur":"1.92","start":"7.88"},{"content":"There’s a flood –","dur":"1.24","start":"10.72"},{"content":"Maurice, they’re not listening.","dur":"1.84","start":"13.96"},{"content":"We’ve got to give them\na good old-fashioned fish slappin’.","dur":"2.8","start":"15.96"},{"content":"Fish Slap!","dur":"1.04","start":"20.52"},{"content":"Fish Slap!","dur":"1","start":"22.32"},{"content":"Fish Slap!","dur":"1.2","start":"24.12"},{"content":"Double Fish Slap!","dur":"1.24","start":"25.84"},{"content":"See, guys? Flood’s here.","dur":"1.56","start":"27.84"},{"content":"Tub Rider!","dur":"2.48","start":"31.56"},{"content":"SEASON 1\nTHE FLOOD","dur":"1","start":"35.32"},{"content":"Because I’m in a tub!","dur":"1.04","start":"36.48"},{"content":"PREPARE TO BATTLE ON A BOAT","dur":"1.48","start":"37.68"}]}}"
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject transcript = jsonObject.getJSONObject("transcript")
JSONArray jsonArray = transcript.getJSONArray("text");
Log.w("aaa",String.valueOf(jsonArray.getJSONObject(0).get("content")));
} catch (JSONException e) {
e.printStackTrace();
}
You need to pass json string to Json object first.
please refer the below code, it might work for you.
try {
JSONObject obj = new JSONObject("{\"transcript\":{\"text\":[{\"content\":\"Flood!\",\"dur\":\"1.76\",\"start\":\"2.28\"},{\"content\":\"Listen up, there�s a flood coming!\",\"dur\":\"2.24\",\"start\":\"4.52\"},{\"content\":\"Oy lads, flood!\",\"dur\":\"1.92\",\"start\":\"7.88\"},{\"content\":\"There�s a flood �\",\"dur\":\"1.24\",\"start\":\"10.72\"},{\"content\":\"Maurice, they�re not listening.\",\"dur\":\"1.84\",\"start\":\"13.96\"},{\"content\":\"We�ve got to give them\\na good old-fashioned fish slappin�.\",\"dur\":\"2.8\",\"start\":\"15.96\"},{\"content\":\"Fish Slap!\",\"dur\":\"1.04\",\"start\":\"20.52\"},{\"content\":\"Fish Slap!\",\"dur\":\"1\",\"start\":\"22.32\"},{\"content\":\"Fish Slap!\",\"dur\":\"1.2\",\"start\":\"24.12\"},{\"content\":\"Double Fish Slap!\",\"dur\":\"1.24\",\"start\":\"25.84\"},{\"content\":\"See, guys? Flood�s here.\",\"dur\":\"1.56\",\"start\":\"27.84\"},{\"content\":\"Tub Rider!\",\"dur\":\"2.48\",\"start\":\"31.56\"},{\"content\":\"SEASON 1\\nTHE FLOOD\",\"dur\":\"1\",\"start\":\"35.32\"},{\"content\":\"Because I�m in a tub!\",\"dur\":\"1.04\",\"start\":\"36.48\"},{\"content\":\"PREPARE TO BATTLE ON A BOAT\",\"dur\":\"1.48\",\"start\":\"37.68\"}]}}");
JSONObject transcriptObject = obj.getJSONObject("transcript");
Log.d("transcript object",transcriptObject.toString());
JSONArray textArray = transcriptObject.getJSONArray("text");
Log.d("text array",textArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
You can use GSON library for json parsing.
Instead of String.valueOf(jsonArray.getJSONObject(0).get("content"))
you could use :
jsonArray.getJSONObject(0).getString("content")
It is possible to retrieve a JSON object without a key name?
One more problem is that it is deep in the hierarchy. Please see this: http://jsonviewer.stack.hu/#http://gateway.marvel.com/v1/public/characters?apikey=2d0af97a020cd072d49059aa0bf13207&hash=ef7184ddbb03ed2f71da0efec112cf41&ts=1495035369
That is an intensively long JSON and has multiple objects.
I am trying to access this part of the JSON: {
"id": 1010699,
"name": "Aaron Stack", ..
I am using the following code:
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("data");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String title = post.optString("results");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I can't access it.
You can use GSON for this
compile 'com.google.code.gson:gson:2.7'
and create POJO class for the corroesponding json result using this link, Just paste your json data and create classes.
For eg your main pojo class name be JsonResponseHolder
And in your java code
try {
JsonResponseHolder jrh = new Gson().fromJson(responseString,
JsonResponseHolder.class);
List<Results> results = jrh.getData().getResults();
/// this will give the result objects
/// and be sure to convert [] arrays to list for better data handling
} catch (JSONException e) {
e.printStackTrace();
}
Hope this will help
I want to send this serialize Json in Soap web service parameter to get data from server. I don know how to serialize Json like below.
I am doing this -
JSONObject jsonObject = new JSONObject();
try {
JSONObject obj = new JSONObject();
//obj.put("MeterSrNo", txtMeterSrMo.getText().toString());
obj.put("MeterSrNo", txtMeterSrMo.getText().toString());
jsonObject.put("obj", obj);
jsonObject.put("SPName", "XXMFU_GETMobilityDetail");
} catch (JSONException e) {
e.printStackTrace();
}
And its giving me below output-
{'obj':{"MeterSrNo":"5"},'SPName':'XXMFU_GETMobilityDetail'}
But i want below output. How can i achieve this?
"{'\obj\':{\"MeterSrNo\":\"5\"},'\SPName\':'XXMFU_GETMobilityDetail'}"
By using Gson Library you can do serialization and desertification.
Serialization
new Gson().toJson(object)
Deserialization
new Gson().fromJson(jsonString, MyClass.class);
Try following way,
JSONObject jsonObject = new JSONObject();
JSONObject jsonMeterObject = new JSONObject();
try {
jsonMeterObject.put("MeterSrNo","5");
jsonObject.put("obj",jsonMeterObject);
jsonObject.put("SPName","XXMFU_GETMobilityDetail");
} catch (JSONException e) {
e.printStackTrace();
}
Output
{
"obj":{
"MeterSrNo":"5"
},
"SPName":"XXMFU_GETMobilityDetail"
}
Purely as an academic exercise I wanted to convert one of my existing GAE applets to return the response back to Android in JSON and parse it accordingly.
The original XML response containing a series of booleans was returned thus:
StringBuilder response = new StringBuilder();
response.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
response.append("<friend-response><added>");
response.append(friendAdded);
response.append("</added><removed>");
response.append(friendRemoved);
response.append("</removed><found>");
response.append(friendFound);
response.append("</found></friend-response>");
I want to replace this with a JSON response that looks something like this:
{ "friendResponse" : [ { "added":true, "removed":false, "found":true } ]}
I think I can generate the array contents as follows (I haven't tested it yet) but I don't know how to create the top-level friendResponse array itself. I can't seem to find any good examples of creating JSON responses in Java using the com.google.appengine.repackaged.org.json library. Can anyone help put me on the right path?
boolean friendAdded, friendRemoved, friendFound;
/* Omitted the code that sets the above for clarity */
HttpServletResponse resp;
resp.setContentType("application/json");
resp.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
try {
//How do I create this as part of a friendResponse array?
json.put("added", friendAdded);
json.put("removed", friendRemoved);
json.put("found", friendFound);
json.write(resp.getWriter());
} catch (JSONException e) {
System.err
.println("Failed to create JSON response: " + e.getMessage());
}
You need to use JSONArray to create the (single-element) array that will store your object:
try {
JSONObject friendResponse = new JSONObject();
friendResponse.put("added", friendAdded);
friendResponse.put("removed", friendRemoved);
friendResponse.put("found", friendFound);
JSONArray friendResponseArray = new JSONArray();
friendResponseArray.put(friendResponse);
JSONObject json = new JSONObject();
json.put("friendResponse", friendResponseArray);
json.write(resp.getWriter());
} catch (JSONException e) {
System.err
.println("Failed to create JSON response: " + e.getMessage());
}
You can use GSON: https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples
With this framework, you can serialize an object to json, and vice versa.
is there any simple example for Android of using JSON in a serialization?
Thanks
We use the gson library for that. Serialization is as simple as calling
new Gson().toJson(obj)
And for deserialization,
new Gson().fromJson(jsonStr, MyClass.class);
If you want to avoid using another library in your Android project just to (de)serialize JSON, you cau use following code as I do.
To serialize
JSONObject json = new JSONObject();
json.put("key", "value");
// ...
// "serialize"
Bundle bundle = new Bundle();
bundle.putString("json", json.toString());
and to deserialize
Bundle bundle = getBundleFromIntentOrWhaterver();
JSONObject json = null;
try {
json = new JSONObject(bundle.getString("json"));
String key = json.getString("key");
} catch (JSONException e) {
e.printStackTrace();
}
There is a simple library to (de)serialize JSON,compatible with android own json library.
// deserialize a java bean to json object
JSONObject studentJson = JsonDeer.toJson(student);
// serialize a java bean from json object
Student student1 = JsonDeer.fromJson(studentJson,Student.class);
library address
protected void onPostExecute(String results) {
if (results!=null) {
try {
Tec tec_m=new Tec();
tec_m=new Gson().fromJson(results, Technician.class);
((AndroidActivity)activity).setData(tec_m);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}