I am trying to fetch all videos of a channel using youtube data api, but my code is giving error and doesn't respond to PAGE token
displayVideos();
}
private void displayVideos ()
{
RequestQueue requestQueue= Volley.newRequestQueue(this);
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
System.out.println(jsonObject.get("nextPageToken"));
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("id")){
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
if (jsonVideoId.has("kind")){
if(jsonVideoId.getString("kind").equals("youtube#video")){
JSONObject jsonObjectSnippet = jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectDefault=jsonObjectSnippet.getJSONObject("thumbnails").getJSONObject("medium");
String video_id=jsonVideoId.getString("videoId");
VideoDetails vd=new VideoDetails();
vd.setVideoId(video_id);
vd.setTitle(jsonObjectSnippet.getString("title"));
vd.setDescription(jsonObjectSnippet.getString("description"));
vd.setUrl(jsonObjectDefault.getString("url"));
videoDetailsoArrayList.add(vd);
}
// recyclerView.setAdapter(adapter);
// adapter.notifyDataSetChanged();
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
the url I am trying to parse is
String url="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCVMWWQ985A_-SESZUy_SsVQ&maxResults=50&pageToken="+nextPageToken+"&order=date&pageToken=CAUQAA&key=API_KEY";
I have been searchingb to apply nextpage token or page token in android studio but couldnt get specific tutorial. there are many examples but being naive in android studio I cant implement it into my code.
Please note that your URL does contain two instances of the parameter pageToken:
"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCVMWWQ985A_-SESZUy_SsVQ&maxResults=50&pageToken="+nextPageToken+"&order=date&pageToken=CAUQAA&key=API_KEY".
It should have only one for that to work OK; to be more precise, your URL should contain only this instance: pageToken="+nextPageToken+".
On the other hand, your code above does not show the loop implementing pagination. That is that you haven't shown the piece of code where you actually assign a valid value to the variable nextPageToken.
Therefore I cannot tell if your program will work or not.
The pagination loop would look like this:
// initially no pageToken
nextPageToken = null;
// URL as above, without the parameter pageToken
url = ...
do {
invoke the API on the URL: url + (nextPageToken != null ? "&pageToken=" + nextPageToken : "")
nextPageToken = jsonObject.get("nextPageToken");
} while (nextPageToken != null)
I am writing automation script to validate json responses of REST APIs and i am using faster xml to serialize and convert java object to json format.
I have a user case where I have to get the json response and add a new array element to an existing array and post it back.
The json response after GET looks like this :
{
"name":"test",
"id":"1234",
"nodes":[
{
"nodeId":"node1"
},
{
"nodeId":"node2"
}
]
}
To this json response, I need to add a third entry for nodes array
{ "nodeId": "node3" } and then post this.
Can someone please help me understand how to add a new array element to an existing array?
You can try:
//Your JSON response will be in this format
String response = "{ \"name\":\"test\", \"id\":\"1234\", \"nodes\":[ { \"nodeId\":\"node1\" }, { \"nodeId\":\"node2\" } ] }";
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray nodesArray = jsonResponse.getJSONArray("nodes");
JSONObject newEntry = new JSONObject();
newEntry.put("nodeId","node3");
nodesArray.put(newEntry);
jsonResponse.put("nodes",nodesArray);
} catch (JSONException e) {
e.printStackTrace();
}
Now you can post your jsonResponse.toString() as required.
I would rather go for cleaner approach, create Object with below structure -
public class Response{
private String name;
private int id;
private List<Node> nodes;
<Getter & Setter>
}
public class Node{
private String nodeId;
}
Serialize the json -
Response response = objectMapper.readValue(responseJson,
Response.class);
Add the new incoming node object to response -
response.getNodes().add(New Node("{new node Value}"));
Deserialize before post -
objectMapper.writeValueAsString(response);
There is some issue with the JSONObjectRequest in Volley library to receive the JSON data. I suppose I am going wrong somewhere in receiving the JSON object in the Java code. Following is my JSON output coming as a response from the php file hosted on server:
{"workers":[
{"id":"1","name":"Raja","phonenumber":"66589952","occupation":"Plumber","location":"Salunke Vihar","rating":"4","Review":"Hard Worker","price":"80"},
{"id":"2","name":"Aman","phonenumber":"789456","occupation":"Plumber","location":"Wakad","rating":"4","Review":"Good","price":"80"}
],
"success":1}
Following is clode from the Java file where I am using the JSON request using Volley library:
JsonObjectRequest jsonRequest = new JsonObjectRequest (Request.Method.POST, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// I should receive the success value 1 here
int success = response.getInt("success");
//and should receive the workers array here
Log.d("response",response.getJSONArray("workers").toString());
Log.d("success",""+success);
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
//Finally initializing our adapter
adapter = new WorkerAdapter(listWorkers);
recyclerView.setAdapter(adapter);
//adapter is working fine
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "get_list");
params.put("service", service);
return params;
}
Running the above code it goes to the error listener and gives the output as org.json.JSONException: End of input at character 0 of.
But if I use StringRequest in place of JsonObjectRequest and receive the JSON response as a string then I am able to receive the output as a String but I can't use it further. So, please let me know where I am going wrong in receiving the JSONdata and suggest me the changes in the code that I must do.
EDIT- I am adding the php file which is returning the JSON object. Please let me know if there is some error over here:
<?php
error_reporting(0);
include("config.php");
if($_SERVER['REQUEST_METHOD']=='POST'){
$tag = $_POST['tag'];
// array for JSON response
$response = array();
if ($tag == 'get_list') {
// Request type is check Login
$service = $_POST['service'];
//echo json_encode($service);
// get all items from myorder table
$result = mysql_query("SELECT * FROM Workers WHERE Occupation = '$service'") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["workers"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$item = array();
$item["id"] = $row["wID"];
$item["pic"] = $row["Pic"];
$item["name"] = $row["Name"];
$item["phonenumber"] = $row["Phone Number"];
$item["occupation"] = $row["Occupation"];
$item["location"] = $row["Location"];
$item["rating"] = $row["Rating"];
$item["Review"] = $row["Review"];
$item["price"] = $row["Price"];
// push ordered items into response array
array_push($response["workers"], $item);
}
// success
$response["success"] = 1;
}
else {
// order is empty
$response["success"] = 0;
$response["message"] = "No Items Found";
}
}
echo json_encode($response);
}
?>
When I ran the api end point I have got the following result instead of the one that you have been telling so. So stop giving irrelevant data.
"Plumber"{"workers":[{"id":"1","pic":"ttp:\/\/vorkal.com\/images\/vorkal_cover.PNG","name":"Raja","phonenumber":"66589952","occupation":"Plumber","location":"Salunke Vihar","rating":"4","Review":"Hard Worker. Very Professional.","price":"80"},{"id":"2","pic":"http:\/\/vorkal.com\/images\/vorkal_cover.PNG","name":"Aman","phonenumber":"789456","occupation":"Plumber","location":"Wakad","rating":"4","Review":"Good","price":"80"}],"success":1}
Where Plumber is not the tag at all, hence throws error as the same is not valid json string. There's error in your server side scripting. I request you to send the complete script without modification.
If you are not getting the JSONObject that means the following is a malformed json. Thus you can try the following code in server side
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = $this->utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
where$d is the string/response. use it as echo json_encode($this->utf8ize($detail));
Also try the following in client side code
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
You may refer the solution to this question here click here
you can use Gson to convert json string to object
Gson gson = new Gson();
GetWorkersResponse getWorkersResponse =gson.fromJson(response,GetWorkersResponse.class);
class GetWorkersResponse {
public boolean success;
public List<Worker> workers = new ArryList<>();
}
It's work for me.
Can you check that server is returning you a JSONObject and not the string? In Volley if the type of response is different then it will return the error.
I'm getting some data from the Trello API over HTTP. So an example of the response would be:
'[{"name":"asd","desc":"yes"},{"name":"xyz","desc":"no"}]'
I'm using the volley library for making the request and getting the response. Is there a way for me to get the response in the form of json objects directly instead of in a string?
If not how should I proceed?
Thanks!
You can use JSONArray(). And then you can use getString() so you can use all string function.
Example code:
JSONArray jsonArray = new JSONArray(responseString);
int i = 0;
while (i <jsonArray.length()) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("name");
String description = jsonObj.getString("desc");
//TODO create your Java object and store these strings into it.
i++;
}
use volley can solve easily.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
//the response is JsonArray
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
}
});
I have String variable called jsonString:
{"phonetype":"N95","cat":"WP"}
Now I want to convert it into JSON Object. I searched more on Google but didn't get any expected answers!
Using org.json library:
try {
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
Log.d("Error", err.toString());
}
To anyone still looking for an answer:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
You can use google-gson. Details:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
Another example for Gson:
Gson is easy to learn and implement, you need to know is the following two methods:
-> toJson() – convert java object to JSON format
-> fromJson() – convert JSON into java object
import com.google.gson.Gson;
public class TestObjectToJson {
private int data1 = 100;
private String data2 = "hello";
public static void main(String[] args) {
TestObjectToJson obj = new TestObjectToJson();
Gson gson = new Gson();
//convert java object to JSON format
String json = gson.toJson(obj);
System.out.println(json);
}
}
Output
{"data1":100,"data2":"hello"}
Resources:
Google Gson Project Home Page
Gson User Guide
Example
There are various Java JSON serializers and deserializers linked from the JSON home page.
As of this writing, there are these 22:
JSON-java.
JSONUtil.
jsonp.
Json-lib.
Stringtree.
SOJO.
json-taglib.
Flexjson.
Argo.
jsonij.
fastjson.
mjson.
jjson.
json-simple.
json-io.
google-gson.
FOSS Nova JSON.
Corn CONVERTER.
Apache johnzon.
Genson.
cookjson.
progbase.
...but of course the list can change.
Java 7 solution
import javax.json.*;
...
String TEXT;
JsonObject body = Json.createReader(new StringReader(TEXT)).readObject()
;
To convert String into JSONObject you just need to pass the String instance into Constructor of JSONObject.
Eg:
JSONObject jsonObj = new JSONObject("your string");
String to JSON using Jackson with com.fasterxml.jackson.databind:
Assuming your json-string represents as this: jsonString = {"phonetype":"N95","cat":"WP"}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Simple code exmpl
*/
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
String phoneType = node.get("phonetype").asText();
String cat = node.get("cat").asText();
I like to use google-gson for this, and it's precisely because I don't need to work with JSONObject directly.
In that case I'd have a class that will correspond to the properties of your JSON Object
class Phone {
public String phonetype;
public String cat;
}
...
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Gson gson = new Gson();
Phone fooFromJson = gson.fromJson(jsonString, Phone.class);
...
However, I think your question is more like, How do I endup with an actual JSONObject object from a JSON String.
I was looking at the google-json api and couldn't find anything as straight forward as
org.json's api which is probably what you want to be using if you're so strongly in need of using a barebones JSONObject.
http://www.json.org/javadoc/org/json/JSONObject.html
With org.json.JSONObject (another completely different API) If you want to do something like...
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
System.out.println(jsonObject.getString("phonetype"));
I think the beauty of google-gson is that you don't need to deal with JSONObject. You just grab json, pass the class to want to deserialize into, and your class attributes will be matched to the JSON, but then again, everyone has their own requirements, maybe you can't afford the luxury to have pre-mapped classes on the deserializing side because things might be too dynamic on the JSON Generating side. In that case just use json.org.
Those who didn't find solution from posted answers because of deprecation issues, you can use JsonParser from com.google.gson.
Example:
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(jsonObject.get("phonetype"));
System.out.println(jsonObject.get("cat"));
you must import org.json
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
} catch (JSONException e) {
e.printStackTrace();
}
Codehaus Jackson - I have been this awesome API since 2012 for my RESTful webservice and JUnit tests. With their API, you can:
(1) Convert JSON String to Java bean
public static String beanToJSONString(Object myJavaBean) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.writeValueAsString(myJavaBean);
}
(2) Convert JSON String to JSON object (JsonNode)
public static JsonNode stringToJSONObject(String jsonString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readTree(jsonString);
}
//Example:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JsonNode jsonNode = stringToJSONObject(jsonString);
Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());
(3) Convert Java bean to JSON String
public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readValue(JSONString, beanClass);
}
REFS:
Codehaus Jackson
JsonNode API - How to use, navigate, parse and evaluate values from a JsonNode object
Tutorial - Simple tutorial how to use Jackson to convert JSON string to JsonNode
Converting String to Json Object by using org.json.simple.JSONObject
private static JSONObject createJSONObject(String jsonString){
JSONObject jsonObject=new JSONObject();
JSONParser jsonParser=new JSONParser();
if ((jsonString != null) && !(jsonString.isEmpty())) {
try {
jsonObject=(JSONObject) jsonParser.parse(jsonString);
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}
return jsonObject;
}
To convert a string to json and the sting is like json. {"phonetype":"N95","cat":"WP"}
String Data=response.getEntity().getText().toString(); // reading the string value
JSONObject json = (JSONObject) new JSONParser().parse(Data);
String x=(String) json.get("phonetype");
System.out.println("Check Data"+x);
String y=(String) json.get("cat");
System.out.println("Check Data"+y);
Use JsonNode of fasterxml for the Generic Json Parsing. It internally creates a Map of key value for all the inputs.
Example:
private void test(#RequestBody JsonNode node)
input String :
{"a":"b","c":"d"}
If you are using http://json-lib.sourceforge.net
(net.sf.json.JSONObject)
it is pretty easy:
String myJsonString;
JSONObject json = JSONObject.fromObject(myJsonString);
or
JSONObject json = JSONSerializer.toJSON(myJsonString);
get the values then with
json.getString(param) or/and json.getInt(param) and so on.
No need to use any external library.
You can use this class instead :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
To convert your JSON string to hashmap use this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(
For setting json single object to list
ie
"locations":{
}
in to List<Location>
use
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
jackson.mapper-asl-1.9.7.jar
NOTE that GSON with deserializing an interface will result in exception like below.
"java.lang.RuntimeException: Unable to invoke no-args constructor for interface XXX. Register an InstanceCreator with Gson for this type may fix this problem."
While deserialize; GSON don't know which object has to be intantiated for that interface.
This is resolved somehow here.
However FlexJSON has this solution inherently. while serialize time it is adding class name as part of json like below.
{
"HTTPStatus": "OK",
"class": "com.XXX.YYY.HTTPViewResponse",
"code": null,
"outputContext": {
"class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
"eligible": true
}
}
So JSON will be cumber some; but you don't need write InstanceCreator which is required in GSON.
Using org.json
If you have a String containing JSON format text, then you can get JSON Object by following steps:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
Now to access the phonetype
Sysout.out.println(jsonObject.getString("phonetype"));
Better Go with more simpler way by using org.json lib. Just do a very simple approach as below:
JSONObject obj = new JSONObject();
obj.put("phonetype", "N95");
obj.put("cat", "WP");
Now obj is your converted JSONObject form of your respective String. This is in case if you have name-value pairs.
For a string you can directly pass to the constructor of JSONObject. If it'll be a valid json String, then okay otherwise it'll throw an exception.