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 Có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"));
Related
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");
}
This is JSON response I am getting.
I want to select first 45 records response then I want to select next 45 and so on.
How can I parse this data?
Help.
{
"data": [
{
"id": "xxxxx"
},
{
"id": "xxxxx"
}
]
}
Something like this I am trying.
try {
JSONObject rob = response.getJSONObject();
JSONArray array = rob.getJSONArray("data");
for(int i=0;i<array.length();i++){
JSONObject friend = array.getJSONObject(i);
Log.d("uid",friend.getString("id"));
}
} catch (JSONException e) {e.printStackTrace();}
I wrote it without any IDE, it just is an idea and not more. You will need to check and write it correctly.
// Fields
final static int ITEMS_PER_REQUEST = 45;
int currentIndex = 0;
// Method body
try {
JSONObject rob = response.getJSONObject();
JSONArray array = rob.getJSONArray("data");
int size = Math.min(array.Length, currentIndex + ITEMS_PER_REQUEST);
while(currentIndex < size;) {
JSONObject friend = array.getJSONObject(currentIndex);
Log.d("uid",friend.getString("id"));
++currentIndex;
}
} catch (JSONException e) {
e.printStackTrace();
}
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();
}
I'm getting this string (from webservice) into a JSONArray,
[{
"textinput": [{
"position": 0,
"dependency": "no",
"id": 0,
"Itype": "textinput"
}, {
"position": 2,
"dependency": "no",
"id": 1,
"Itype": "textinput"
}]
}, {
"textarea": [{
"position": 1,
"type": "textarea",
"dependency": "no",
"id": 0
}]
}]
I need to sort the array by ascending order based on key-"position"
I am using org.json library, the below code is the one so far the code i used
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
Collections.sort( jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get("position");
valB = (String) b.get("position");
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonList.get(i));
}
AALso tried other links in the site.
please help
Try TreeMap, it will automatically sort the array for you. All you have to do is make "position" the Key of TreeMap and JSONObject the value. The treemap will arrange the values in ascending order of the keys.And then you can retrieve the JSONObject values from the treemap.
private TreeMap<Integer,JSONObject> sortedarray = new TreeMap<Integer,JONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
sortedarray.put(Integer.parseInt(jsonArray.getJSONObject(i).get("position")+""),jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
Now if you want it to be a jsonArray only..
JSONArray sortedJsonArray = new JSONArray();
for(int x = 0; x<sortedarray.size();x++)
{
//assuming that positions you get in JSON are always complete like 1,2,3,4,....,10,...,100.
sortedJsonArray.put(sortedarray.get(x));
//assuming that positions you get in JSON are not always complete like 1,3,4,..,10,13,...,100.( misses a few numbers in between like 2 and 11 in this case)
sortedJsonArray.put(sortedarray.get(Integer.parseInt(advanceplay.get(advanceplay.keySet().toArray()[i]))));
}
In the Result String i have entire data for that i'm parsing ,i need to print Current Conditions inside values.
current_condition": [ {"cloudcover": "75", "humidity": "71", "observation_time": "06:55 AM", "precipMM": "0.6", "pressure": "1009", "temp_C": "32", "temp_F": "90", "visibility": "10", "weatherCode": "116", "weatherDesc": [ {"value": "Partly Cloudy" } ], "weatherIconUrl": [ {"value": "http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" } ], "winddir16Point": "S", "winddirDegree": "170", "windspeedKmph": "9", "windspeedMiles": "6" } ]
This is my json array ,here i need cloudcover ,weatherDescarrays inside values,how can i print those values.
Here what i did is
JSONParser parser = new JSONParser();
Object obj1 = parser.parse(Result);
JSONObject jobj = (JSONObject) obj1;
JSONObject dataResult = (JSONObject) jobj.get("data");
JSONArray current_condition = (JSONArray) dataResult.get("current_condition");
//out.println(current_condition);
for (int i = 0; i < current_condition.size(); i++) {
}
inside for loop how to repeat and print values ,could anybody help me,thanks in advance.
Assuming that you are using org.json, I would iterate over the array as follows:
public static void main(String[] args) {
String json = "{ \"data\": { \"current_condition\": [ {\"cloudcover\": \"75\", \"humidity\": \"71\", \"observation_time\": \"06:55 AM\", \"precipMM\": \"0.6\", \"pressure\": \"1009\", \"temp_C\": \"32\", \"temp_F\": \"90\", \"visibility\": \"10\", \"weatherCode\": \"116\", \"weatherDesc\": [ {\"value\": \"Partly Cloudy\" } ], \"weatherIconUrl\": [ {\"value\": \"http:\\/\\/cdn.worldweatheronline.net\\/images\\/wsymbols01_png_64\\/wsymbol_0002_sunny_intervals.png\" } ], \"winddir16Point\": \"S\", \"winddirDegree\": \"170\", \"windspeedKmph\": \"9\", \"windspeedMiles\": \"6\" } ]}}";
try {
JSONObject jObj = new JSONObject(json);
JSONObject dataResult = jObj.getJSONObject("data");
JSONArray jArr = (JSONArray) dataResult.getJSONArray("current_condition");
for(int i = 0; i < jArr.length();i++) {
JSONObject innerObj = jArr.getJSONObject(i);
for(Iterator it = innerObj.keys(); it.hasNext(); ) {
String key = (String)it.next();
System.out.println(key + ":" + innerObj.get(key));
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Are you using json simple?, if yes, then try :
for (JSONObject object : current_condition) {
System.out.println("cloudcover : " + object.get("cloudcover"));
System.out.println("humidity : " + object.get("humidity"));
}