Can't get value from JSON Data - YouTube API - - java

I'v try to get an value from a json data (YouTube V3 API).
String jsonText = readFromUrl(channerUrl);// channerUrl = Youtube V3 API Link
JSONObject json = new JSONObject(jsonText);
System.out.println(json.getString("videoId"));
But i have this in my log :
I/System.out: org.json.JSONException: No value for videoId
The data from YouTube is :
{
"kind": "youtube#playlistItemListResponse",
"etag": "\"xxxx"",
"nextPageToken": "xxx",
"pageInfo": {
"totalResults": 321,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#playlistItem",
"etag": "\"xxxx"",
"id": "xxxx",
"contentDetails": {
"videoId": "The Value Want"
}
}
]
}
Why i have No value for videoId ?
Thank you
EDIT (didn't work too) : (jsonText) is the link of the JSON Data
JSONObject json = new JSONObject(jsonText);
List<String> list = new ArrayList<String>();
JSONArray array = json.getJSONArray("items");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("contentDetails"));
System.out.println(json.getString("contentDetails"));
}

Because videoId is under items object.
Get item first then get its first child then fet the videoId
Edit: use
array.getJSONObject(i).getJSONObject("contentDetails").getString("videoId")
And remove the println line
Then outside the loop just print the list that contains the videoIds

use this code :
JSONObject json = new JSONObject(jsonText);
List<String> list = new ArrayList<String>();
JSONArray array = null;
try {
array = json.getJSONArray("items");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0 ; i < array.length() ; i++){
// list.add(array.getJSONObject(i).getString("contentDetails"));
try {
System.out.println(array.getJSONObject(i).getJSONObject("contentDetails").getString("videoId"));
} catch (JSONException e) {
e.printStackTrace();
}
}

try
{
JSONObject mJsonObject = new JSONObject(strValue);
JSONArray items = mJsonObject.getJSONArray("items");
String nextToken = mJsonObject.getString("nextPageToken").toString();
for(int i = 0;i<items.length();i++)
{
JSONObject snipetts = items.getJSONObject(i);
JSONObject snipet = snipetts.getJSONObject("snippet");
JSONObject thumbnails = snipet.getJSONObject("thumbnails");
JSONObject highImage = thumbnails .getJSONObject("high");
String title = snipet.get("title").toString();
String urlImage = highImage.get("url").toString();
String videoID = snipetts.getString("id");
String description = snipet.getString("description");
String publishDate = snipet.getString("publishedAt");
}
}
catch (Exception e)
{
e.printStackTrace();
}

Related

Transform a JsonArray into an ArrayList

I have this json that i got using the YoutubeAPI :
{
"items": [
{
"id": {
"videoId": "ob1ogBV9_iE"
},
"snippet": {
"title": "13 estrellas ",
"description": "Pueden encontrar estas "
}
},
{
"id": {
"videoId": "o9vsXyrola4"
},
"snippet": {
"title": "Rayos CoĢsmicos ",
"description": "Este es un programa piloto "
}
}
]
}
i want to save the fiel "id" on an ArrayList but i have some problems this is the code im using:
JSONArray jsonArray = myResponse.getJSONArray("items");
In this line im creating an JSONarray with the JSONobject i created first
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
list.add(json.getString("videoID"));
} catch (JSONException e) {
e.printStackTrace();
}
}
My question is how can i access to this field? and how can i save it
You've got two main issues. The first is that "videoID" and "videoId" are not the same string. So you're checking for a key that doesn't exist.
Your second problem is that the "videoId" key doesn't exist in the top level object, it's inside the "id" object, so you need to drill down an extra layer to get it:
JSONArray jsonArray = myResponse.getJSONArray("items");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
JSONObject id = json.getJSONObject("id");
list.add(id.getString("videoId"));
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println(list); // [ob1ogBV9_iE, o9vsXyrola4]
Try with correct case for videoId, like
list.add(json.getString("videoId"));

How to get values from json String

I have a json string string from which I want to get the values. It is in key pair form so I want the values for each key.
I tried to get the values but I am not getting it.
Json String is like :
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
I want to get values of "Name", "Address", "Company" etc.
I tried to get like this:
JSONArray array;
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
array = object.getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(i);
edt_FirstName.setText(object.getString("Name"));
}
} catch (JSONException e) {
}
Can anyone help me out please? Thank you..
EDIT:
I tried to check values like this:
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(0);
String type = subObject1.getString("type");
String value = subObject1.getString("value");
if (type.equals("Name")) {
edt_FirstName.setText(value);
}
if(type.equals("Address"))
{
edt_address.setText(value);
}
if(type.equals("Company"))
{
edt_company.setText(value);
}
if(type.equals("Mobile"))
{
edt_Mobile.setText(value);
}
}
I want to get all the values from field array and set to the text view, but I am getting only the Name value and not the others.
Also I could get one field as twice like Mobile I can get twice, so I want to combine both the Mobile values and show it.
So your json object is as follow:
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
You first need to get "document" as JSONObject and then get "businessCard" as JSONObject and then you can get "field" as JSONArray:
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
JSONArray array = object.getJSONObject("document").getJSONObject("businessCard").getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject = array.getJSONObject(i);
String type = subObject.getString("type");
String value = subObject.getString("value");
if (type.equals("Name")) {
String prevValue = edt_FirstName.getText();
edt_FirstName.setText((TextUtils.isEmpty(prevValue) ? "" : prevValue + ",") + value);
}
}
} catch (JSONException e) { }
}
Try this code, Hope it will help you.
try
{
JSONObject jsonObject = new JSONObject();
JSONObject documentObject = jsonObject.getJSONObject("document");
JSONObject businessCardObject = documentObject.getJSONObject("businessCard");
String imgRotation = businessCardObject.getString("imageRotation");
JSONArray array = businessCardObject.getJSONArray("field");
for (int i = 0; i < array.length() ; i++)
{
JSONObject arrObj = array.getJSONObject(i);
String type = arrObj.getString("type");
String value = arrObj.getString("value");
Log.e(TAG, "type=="+type);
Log.e(TAG, "value=="+value);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
here is code
private void convertJsonToDto(String jsonNewString) {
JSONObject jsonObj = new JSONObject(jsonNewString);
String RecordLocator = (String) jsonObj.get("obj");
String FirstName = (String) jsonObj.getJSONObject("Customer").get("FirstName");
JSONArray array = new JSONObject(jsonNewString).getJSONArray("Array");
JSONObject jsonObject = array.getJSONObject(0);
String str = jsonObject.getString("object");
}

my json parser for jsonarry just get the first element

i have parser function that parse json array and return arrays that i use it in a list adapter and then the adapter is used by a recyclerview .it's giving me the actual length but only the first element of the arrays is filled while the others return NULL
that is my code
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
the json is
{
"result": [{
"item_id": "10",
"owner": "user",
"item_type_id": "1",
"url1": "http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "jc",
"price": "76"
}, {
"item_id": "12",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "nzbsbsb",
"price": "0"
}, {
"item_id": "13",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "uygf",
"price": "0"
}]
}
and this screenshot of the list
enter image description here
it's not suggested parsing json yourself ,use a Json Parse Util such as Gson or fastJson instead .
I used your code, debug, and found values are updated their is no error with JSON paring, So check your recycler view adapter code or share it
Replace this line
jo = userss.getJSONObject(4);
with this
jo = userss.getJSONObject(i);
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
}
the problem with ur code is you use hardcode value 4
jo = userss.getJSONObject(4);
insted of this use
jo = userss.getJSONObject(i);
at each and every time you are parsing the index 4 jsonObject information
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if you use this type of parsing it may lead to null pointer exception
You can parse above JSON as follows
private void jsonParse(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
if (object != null) {
String itemId = object.getString("item_id");
String owner = object.getString("owner");
String item_type_id = object.getString("item_type_id");
String url1 = object.getString("url1");
String name = object.getString("name");
String price = object.getString("price");
}
}
}
}
i was receiving a parameter that wasn't being sent by the jsonarray
item_place[i] = jo.getString("place")

Parsing JSON Not Showing out of range

I'm working on parsing JSON file in my java and the JSON file goes like this
{"System":[{"System1":{"DisplayName":"fabcd","InternalName":"AD","SystemCode":"0001","SystemName":"vnid"},"System2":{"DisplayName":"akdfkajfl","InternalName":"AD","SystemCode":"0001","SystemName":"kjdfkafdk"}}]}
I cannot access the all objects inside "System" array. Please help me on this. My code is this
Systems = jObj.getJSONArray("System");
Log.d("Array", Systems.toString());
JSONObject first = Systems.getJSONObject(0);
Log.d("CSystems",first.toString());
// looping through All Contacts
for(int i = 0; i <=Systems.length(); i++){
JSONObject c = Systems.getJSONObject(i);
Log.d("SubSystems", Systems.getString(0));
}
Thanks.
Shouldn't for loop be looping over first instead of Systems? (With changes to account for the fact it's an object, not an array.)
To parse
try
{
JSONObject jObj = new JSONObject("My Json string");
JSONArray jr = jObj.getJSONArray("System");
JSONObject jb= jr.getJSONObject(0);
JSONObject system1 = jb.getJSONObject("System1");
String name = system1.getString("DisplayName");
String internalname = system1.getString("InternalName");
String SystemCode = system1.getString("SystemCode");
String SystemName = system1.getString("SystemName");
JSONObject system2 = jb.getJSONObject("System2");
String name1= system2.getString("DisplayName");
String internalname1 = system2.getString("InternalName");
String SystemCode1 = system2.getString("SystemCode");
String SystemName1 = system2.getString("SystemName");
Log.i("..........",name+"..."+internalname+"..."+SystemCode+"..."+SystemName);
Log.i("..........",name1+"..."+internalname1+"..."+SystemCode1+"..."+SystemName1);
}catch(Exception e)
{
e.printStackTrace();
}
or
Same as above.
try
{
JSONObject jObj = new JSONObject("My json string");
JSONArray jr = jObj.getJSONArray("System");
for(int i = 0; i<jr.length(); i++){
JSONObject c = jr.getJSONObject(i);
for(int j = 1;j<3; j++){
JSONObject jb = c.getJSONObject("System"+(j));
Log.i("SubSystems", jb.getString("DisplayName"));
Log.i("SubSystems", jb.getString("InternalName"));
Log.i("SubSystems", jb.getString("SystemCode"));
Log.i("SubSystems", jb.getString("SystemName"));
}
}
}catch(Exception e)
{
e.printStackTrace();
}
or change your json to
{
"System": [
{
"DisplayName": "fabcd",
"InternalName": "AD",
"SystemCode": "0001",
"SystemName": "vnid"
},
{
"DisplayName": "akdfkajfl",
"InternalName": "AD",
"SystemCode": "0001",
"SystemName": "kjdfkafdk"
}
]
}
To parse. Changing json to above parsing is much more easier.
try
{
JSONObject jObj = new JSONObject("My json string);
JSONArray jr = jObj.getJSONArray("System");
for(int i = 0; i<jr.length(); i++){
JSONObject c = jr.getJSONObject(i);
Log.i("SubSystems", c.getString("DisplayName"));
Log.i("SubSystems", c.getString("InternalName"));
Log.i("SubSystems", c.getString("SystemCode"));
Log.i("SubSystems", c.getString("SystemName"));
}
}catch(Exception e)
{
e.printStackTrace();
}
You can also look at https://code.google.com/p/google-gson/

Add JSON entry into an array to use in ListView

I have the following code which gets the number how many times a select entry appears:
int k = 0;
int j = 0;
try {
jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the josn object
if(jsonObj.getString("type").equals("image")) { // compare for the key-value
k++;
}
if(jsonObj.getString("type").equals("text")) { // compare for the key-value
j++;
}
}
Toast.makeText(getApplicationContext(), String.valueOf(k), 2000).show();
Toast.makeText(getApplicationContext(), String.valueOf(j), 2000).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My JSON file is:
[
{
"id": "12",
"type": "text",
"data": "This is a test"
},
{
"id": "5465465",
"type": "image",
"data": "http://pagesbyz.com/theImages/gallery/portfolio_app07.png"
},
{
"id": "982",
"type": "text",
"data": "THIS IS A TEST TEXT"
},
{
"id": "5500",
"type": "text",
"data": "http://pagesbyz.com/theImages/gallery/portfolio_app03.png"
}
]
So... k = 1 and j = 3
How can I get the entire array for the matched entry?
For example once the type equals image I want an array set up to hold the information.
How do I translate the following in Java?
for (as many times an "image" entry appears) {
if ( type == "image") {
imgarr[index found][id] = "5465465";
imgarr[index found][type] = "image";
imgarr[index found][data] = "http://pagesbyz.com/theImages/gallery/portfolio_app07.png";
}
}
for (as many times an "text" entry appears) {
if ( type == "text") {
txtarr[index found][id] = "12";
txtarr[index found][type] = "text";
txtarr[index found][data] = "This is a test";
txtarr[index found][id] = "082";
txtarr[index found][id] = "text";
txtarr[index found][id] = "THIS IS A TEST TEXT";
and so forth...
}
}
And the same for type equals "text"?
create 2 new jsonArray variables, one for image and one for type, whenever the type is image add the object to jsonimage and same for jsontext
try {
JSONArray jsonimage = new JSONArray();
JSONArray jsontext = new JSONArray();
jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the josn object
if(jsonObj.getString("type").equals("image")) { // compare for the key-value
jsonimage.put(jsonObj);
k++;
}
if(jsonObj.getString("type").equals("text")) { // compare for the key-value
jsontext.put(jsonObj);
j++;
}
}
Toast.makeText(getApplicationContext(), String.valueOf(k), 2000).show();
Toast.makeText(getApplicationContext(), String.valueOf(j), 2000).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hope this is what you are looking for or give you a hint.
EDIT:
to add the jsonArray to the listview, you can either create a hashMap or simply create String of strings for each entry in the JSONArray.
String sId = new String[jsonimage.length()];
String sType = new String[jsonimage.length()];
String sData = new String[jsonimage.length()];
for (int i = 0 ; i < jsonimage.length(); i++)
{
JSONObject c = jsonimage.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
String data = c.getString("data");
sId[i] = id;
sType[i] = type;
sData[i] = data;
}
then after you having your data from the JSONArray...
have a custom view that holds 3 textview and add this
listView.setAdapter(new CustomAdapter(yourClass.this));
and simply add the generated String[position] in getView of the CustomAdapter

Categories