Convert string to JSON array - java

I have the following string of a JSON from a web service and am trying to convert this to a JSONarray
{
"locations": [
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
}
]
}
I validated this String online, it seems to be correct. Now I am using the following code in android development to utilise
JSONArray jsonArray = new JSONArray(readlocationFeed);
This throws exception a type mismatch Exception.

Here you get JSONObject so change this line:
JSONArray jsonArray = new JSONArray(readlocationFeed);
with following:
JSONObject jsnobject = new JSONObject(readlocationFeed);
and after
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}

Input String
[
{
"userName": "sandeep",
"age": 30
},
{
"userName": "vivan",
"age": 5
}
]
Simple Way to Convert String to JSON
public class Test
{
public static void main(String[] args) throws JSONException
{
String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}] ";
JSONArray jsonArr = new JSONArray(data);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println(jsonObj);
}
}
}
Output
{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}

Using json lib:-
String data="[{"A":"a","B":"b","C":"c","D":"d","E":"e","F":"f","G":"g"}]";
Object object=null;
JSONArray arrayObj=null;
JSONParser jsonParser=new JSONParser();
object=jsonParser.parse(data);
arrayObj=(JSONArray) object;
System.out.println("Json object :: "+arrayObj);
Using GSON lib:-
Gson gson = new Gson();
String data="[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":\"d\",\"E\":\"e\",\"F\":\"f\",\"G\":\"g\"}]";
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(data);

you will need to convert given string to JSONObject instead of JSONArray because current String contain JsonObject as root element instead of JsonArray :
JSONObject jsonObject = new JSONObject(readlocationFeed);

String b = "[" + readlocationFeed + "]";
JSONArray jsonArray1 = new JSONArray(b);
jsonarray_length1 = jsonArray1.length();
for (int i = 0; i < jsonarray_length1; i++) {
}
or convert it in JSONOBJECT
JSONObject jsonobj = new JSONObject(readlocationFeed);
JSONArray jsonArray = jsonobj.getJSONArray("locations");

Try this piece of code:
try {
Log.e("log_tag", "Error in convert String" + result.toString());
JSONObject json_data = new JSONObject(result);
String status = json_data.getString("Status");
{
String data = json_data.getString("locations");
JSONArray json_data1 = new JSONArray(data);
for (int i = 0; i < json_data1.length(); i++) {
json_data = json_data1.getJSONObject(i);
String lat = json_data.getString("lat");
String lng = json_data.getString("long");
}
}
}

if the response is like this
"GetDataResult": "[{\"UserID\":1,\"DeviceID\":\"d1254\",\"MobileNO\":\"056688\",\"Pak1\":true,\"pak2\":true,\"pak3\":false,\"pak4\":true,\"pak5\":true,\"pak6\":false,\"pak7\":false,\"pak8\":true,\"pak9\":false,\"pak10\":true,\"pak11\":false,\"pak12\":false}]"
you can parse like this
JSONObject jobj=new JSONObject(response);
String c = jobj.getString("GetDataResult");
JSONArray jArray = new JSONArray(c);
deviceId=jArray.getJSONObject(0).getString("DeviceID");
here the JsonArray size is 1.Otherwise you should use for loop for getting values.

It's a very simple way to convert:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
class Usuario {
private String username;
private String email;
private Integer credits;
private String twitter_username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getCredits() {
return credits;
}
public void setCredits(Integer credits) {
this.credits = credits;
}
public String getTwitter_username() {
return twitter_username;
}
public void setTwitter_username(String twitter_username) {
this.twitter_username = twitter_username;
}
#Override
public String toString() {
return "UserName: " + this.getUsername() + " Email: " + this.getEmail();
}
}
/*
* put string into file jsonFileArr.json
* [{"username":"Hello","email":"hello#email.com","credits"
* :"100","twitter_username":""},
* {"username":"Goodbye","email":"goodbye#email.com"
* ,"credits":"0","twitter_username":""},
* {"username":"mlsilva","email":"mlsilva#email.com"
* ,"credits":"524","twitter_username":""},
* {"username":"fsouza","email":"fsouza#email.com"
* ,"credits":"1052","twitter_username":""}]
*/
public class TestaGsonLista {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Temp\\jsonFileArr.json"));
JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement str = jsonArray.get(i);
Usuario obj = gson.fromJson(str, Usuario.class);
System.out.println(obj);
System.out.println(str);
System.out.println("-------");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

You can do the following:
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}

If having following JSON from web service, Json Array as a response :
[3]
0: {
id: 2
name: "a561137"
password: "test"
firstName: "abhishek"
lastName: "ringsia"
organization: "bbb"
}-
1: {
id: 3
name: "a561023"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}-
2: {
id: 4
name: "a541234"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}
have To Accept it first as a Json Array ,then while reading its Object have to use Object Mapper.readValue ,because Json Object Still in String .
List<User> list = new ArrayList<User>();
JSONArray jsonArr = new JSONArray(response);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
ObjectMapper mapper = new ObjectMapper();
User usr = mapper.readValue(jsonObj.toString(), User.class);
list.add(usr);
}
mapper.read is correct function ,if u use mapper.convert(param,param) . It will give u error .

Related

Fetching JSON from inside a JSON array

I have the following JSON
"music": [
{
"play_offset_ms":10780,
"artists":[
{
"name":"Adele"
}
],
"lyrics":{
"copyrights":[
"Sony/ATV Music Publishing LLC",
"Universal Music Publishing Group"
]
},
"acrid":"6049f11da7095e8bb8266871d4a70873",
"album":{
"name":"Hello"
},
"label":"XL Recordings",
"external_ids":{
"isrc":"GBBKS1500214",
"upc":"886445581959"
},
"result_from":3,
"contributors":{
"composers":[
"Adele Adkins",
"Greg Kurstin"
],
"lyricists":[
"ADELE ADKINS",
"GREGORY KURSTIN"
]
},
"title":"Hello",
"duration_ms":295000,
"score":100,
"external_metadata":{
"deezer":{
"track":{
"id":"110265034"
},
"artists":[
{
"id":"75798"
}
],
"album":{
"id":"11483764"
}
},
"spotify":{
"track":{
"id":"4aebBr4JAihzJQR0CiIZJv"
},
"artists":[
{
"id":"4dpARuHxo51G3z768sgnrY"
}
],
"album":{
"id":"7uwTHXmFa1Ebi5flqBosig"
}
},
"musicstory":{
"track":{
"id":"13106540"
},
"release":{
"id":"2105405"
},
"album":{
"id":"931271"
}
},
"youtube":{
"vid":"YQHsXMglC9A"
}
},
"release_date":"2015-10-23"
}
]
I want to fetch the value vid from the youtube object in external_metadata. I am getting other required values but couldn't get the youtube id with what I tried. Just attaching a code snippet of what I tried.
I tried the following code:
try {
JSONObject j = new JSONObject(result);
JSONObject j1 = j.getJSONObject("status");
int j2 = j1.getInt("code");
if(j2 == 0){
JSONObject metadata = j.getJSONObject("metadata");
//
if (metadata.has("music")) {
wave.setVisibility(View.GONE);
JSONArray musics = metadata.getJSONArray("music");
for(int i=0; i<musics.length(); i++) {
JSONObject tt = (JSONObject) musics.get(i);
String title = tt.getString("title");
JSONArray artistt = tt.getJSONArray("artists");
JSONObject art = (JSONObject) artistt.get(0);
String artist = art.getString("name");
JSONObject extMETA = tt.getJSONObject("external_metadata");
JSONObject youtube = extMETA.getJSONObject("youtube");
String ytID = youtube.getString("vid");}}
I did not get the expected output with what i tried , i know i am doing something wrong. Need your guidance.
I tried to run your code with sample JSON you have provided and It seems to work perfectly fine. I used google's gson library.
Below is the complete code.
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String jsonString = "{ \"music\": [{ \"play_offset_ms\": 10780, \"artists\": [{ \"name\": \"Adele\" }], \"lyrics\": { \"copyrights\": [ \"Sony/ATV Music Publishing LLC\", \"Universal Music Publishing Group\" ] }, \"acrid\": \"6049f11da7095e8bb8266871d4a70873\", \"album\": { \"name\": \"Hello\" }, \"label\": \"XL Recordings\", \"external_ids\": { \"isrc\": \"GBBKS1500214\", \"upc\": \"886445581959\" }, \"result_from\": 3, \"contributors\": { \"composers\": [ \"Adele Adkins\", \"Greg Kurstin\" ], \"lyricists\": [ \"ADELE ADKINS\", \"GREGORY KURSTIN\" ] }, \"title\": \"Hello\", \"duration_ms\": 295000, \"score\": 100, \"external_metadata\": { \"deezer\": { \"track\": { \"id\": \"110265034\" }, \"artists\": [{ \"id\": \"75798\" }], \"album\": { \"id\": \"11483764\" } }, \"spotify\": { \"track\": { \"id\": \"4aebBr4JAihzJQR0CiIZJv\" }, \"artists\": [{ \"id\": \"4dpARuHxo51G3z768sgnrY\" }], \"album\": { \"id\": \"7uwTHXmFa1Ebi5flqBosig\" } }, \"musicstory\": { \"track\": { \"id\": \"13106540\" }, \"release\": { \"id\": \"2105405\" }, \"album\": { \"id\": \"931271\" } }, \"youtube\": { \"vid\": \"YQHsXMglC9A\" } }, \"release_date\": \"2015-10-23\" }] }";
public static void main(String[] args) throws Exception {
System.out.println("START");
readJson(jsonString);
System.out.println("END");
}
public static void readJson(String jsonString) throws Exception {
JsonObject metadata = new JsonParser().parse(jsonString).getAsJsonObject();
JsonArray musics = metadata.get("music").getAsJsonArray();
for (int i = 0; i < musics.size(); i++) {
JsonObject tt = musics.get(i).getAsJsonObject();
String title = tt.get("title").getAsString();
JsonArray artistt = tt.get("artists").getAsJsonArray();
JsonObject art = artistt.get(0).getAsJsonObject();
String artist = art.get("name").getAsString();
JsonObject extMETA = tt.get("external_metadata").getAsJsonObject();
JsonObject youtube = extMETA.get("youtube").getAsJsonObject();
String ytID = youtube.get("vid").getAsString();
System.out.println("ytID => "+ ytID);
}
}
}
Output:
Verify that the metadata variable has its value.
JSONObject jsonObject = new JSONObject(json);
Log.e("json structure : ", jsonObject.toString());
Use the following code when importing Json File from "Assets".
InputStream inputStream = getAssets().open("item.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
json = new String(buffer, StandardCharsets.UTF_8);
If you have a Gson library, you can also access it in the "Class" format.
Gson gson = new Gson();
ItemVO itemVO = gson.fromJson(json, new TypeToken<ItemVO>() {
}.getType());
if (!itemVO.name != null) {
Log.e("name : ", itemVO.name);
} else {
Log.e("name : ", "name is Null");
}
Actual problem is in your JSONObject creation from sample data. Check below:
String data = "{\"metadata\":{\"timestamp_utc\":\"2020-01-02 09:40:56\",\"music\":[{\"play_offset_ms\":10780,\"artists\":[{\"name\":\"Adele\"}],\"lyrics\":{\"copyrights\":[\"Sony/ATV Music Publishing LLC\",\"Universal Music Publishing Group\"]},\"acrid\":\"6049f11da7095e8bb8266871d4a70873\",\"album\":{\"name\":\"Hello\"},\"label\":\"XL Recordings\",\"external_ids\":{\"isrc\":\"GBBKS1500214\",\"upc\":\"886445581959\"},\"result_from\":3,\"contributors\":{\"composers\":[\"Adele Adkins\",\"Greg Kurstin\"],\"lyricists\":[\"ADELE ADKINS\",\"GREGORY KURSTIN\"]},\"title\":\"Hello\",\"duration_ms\":295000,\"score\":100,\"external_metadata\":{\"deezer\":{\"track\":{\"id\":\"110265034\"},\"artists\":[{\"id\":\"75798\"}],\"album\":{\"id\":\"11483764\"}},\"spotify\":{\"track\":{\"id\":\"4aebBr4JAihzJQR0CiIZJv\"},\"artists\":[{\"id\":\"4dpARuHxo51G3z768sgnrY\"}],\"album\":{\"id\":\"7uwTHXmFa1Ebi5flqBosig\"}},\"musicstory\":{\"track\":{\"id\":\"13106540\"},\"release\":{\"id\":\"2105405\"},\"album\":{\"id\":\"931271\"}},\"youtube\":{\"vid\":\"YQHsXMglC9A\"}},\"release_date\":\"2015-10-23\"}]},\"cost_time\":0.2110002040863,\"status\":{\"msg\":\"Success\",\"version\":\"1.0\",\"code\":0},\"result_type\":0}";
try {
JSONObject jsonObject = new JSONObject(data);
JSONObject metadata = jsonObject.getJSONObject("metadata");
JSONArray musics = metadata.getJSONArray("music");
for (int i = 0; i < musics.length(); i++) {
JSONObject tt = (JSONObject) musics.get(i);
String title = tt.getString("title");
JSONArray artistt = tt.getJSONArray("artists");
JSONObject art = (JSONObject) artistt.get(0);
String artist = art.getString("name");
JSONObject extMETA = tt.getJSONObject("external_metadata");
JSONObject youtube = extMETA.getJSONObject("youtube");
String ytID = youtube.getString("vid");
Log.v("VID", ytID);
}
} catch (Exception ex) {
ex.printStackTrace();
}

How to make a dictionary application using Oxford Dictionary api?

This is the code which I got from the documentations, I get that, I receive the result in JSON format. But I only need the meaning of the word. So can anyone tell me how do I extract only the meaning of the searched word, rather getting the whole JSON file. I am new to android development, Please help me.
package com.example.hsekar.dictionarytestbeta;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new CallbackTask().execute(dictionaryEntries());
}
private String dictionaryEntries() {
final String language = "en";
final String word = "Ace";
final String word_id = word.toLowerCase(); //word id is case sensitive and lowercase is required
return "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id;
}
//in android calling network requests on the main thread forbidden by default
//create class to do async job
private class CallbackTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
//TODO: replace with your own app id and app key
final String app_id = "10742428";
final String app_key = "ada344f3a7a7c7de0315fb78c5c9d6f9";
try {
URL url = new URL(params[0]);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setRequestProperty("app_id",app_id);
urlConnection.setRequestProperty("app_key",app_key);
// read the output from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("This will be my result",result);
}
}
}
The following is my output. I am just printing it in the Logcat but once I get the concept , I will start working on the project.
This will be my result: {
"metadata": {
"provider": "Oxford University Press"
},
"results": [
{
"id": "ace",
"language": "en",
"lexicalEntries": [
{
"entries": [
{
"etymologies": [
"Middle English (denoting the ‘one’ on dice): via Old French from Latin as ‘unity, a unit’"
],
"grammaticalFeatures": [
{
"text": "Singular",
"type": "Number"
}
],
"homographNumber": "000",
"senses": [
{
"definitions": [
"a playing card with a single spot on it, ranked as the highest card in its suit in most card games"
],
"domains": [
"Cards"
],
"examples": [
{
"registers": [
"figurative"
],
"text": "life had started dealing him aces again"
},
{
"text": "the ace of diamonds"
}
],
"id": "m_en_gbus0005680.006"
},
{
"definitions": [
"a person who excels at a particular sport or other activity"
],
"domains": [
"Sport"
],
"examples": [
{
"text": "a motorcycle ace"
}
],
"id": "m_en_gbus0005680.010",
"registers": [
"informal"
],
"subsenses": [
{
"definitions": [
"a pilot who has shot down many enemy aircraft"
],
"domains": [
"Air Force"
],
"examples": [
{
"text": "a Battle of Britain ace"
}
],
"id": "m_en_gbus0005680.011"
}
]
},
{
"definitions": [
"(in tennis and similar games) a service that an opponent is unable to return and thus wins a point"
],
"domains": [
"Tennis"
So my question is how do I extract only the 'meaning' part from this output?
The Json result that you have mentioned is incomplete.the objects in the result are not closed.By the way this is how you get the results from json string.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject js = new JSONObject(result);
JSONArray results = js.getJSONArray("results");
for(int i = 0;i<results.length();i++){
JSONObject lentries = results.getJSONObject(i);
JSONArray la = lentries.getJSONArray("lexicalEntries");
for(int j=0;j<la.length();j++){
JSONObject entries = la.getJSONObject(j);
JSONArray e = entries.getJSONArray("entries");
for(int i1=0;i1<e.length();i1++){
JSONObject senses = la.getJSONObject(i1);
JSONArray s = entries.getJSONArray("senses");
JSONObject d = s.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def = de.getString(0);
}
}
}
Log.e("def",def);
} catch (JSONException e) {
e.printStackTrace();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Log.d("This will be my result",result);
String def = "";
try {
JSONObject js = new JSONObject(result);
JSONArray results = js.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject lentries = results.getJSONObject(i);
JSONArray la = lentries.getJSONArray("lexicalEntries");
for (int j = 0; j < la.length(); j++) {
JSONObject entries = la.getJSONObject(j);
JSONArray e = entries.getJSONArray("entries");
for (int k= 0; k < e.length(); k++) {
JSONObject senses = e.getJSONObject(k);
JSONArray s = senses.getJSONArray("senses");
JSONObject d = s.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def = de.getString(0);
}
}
}
Log.e("def", def);
} catch (JSONException e) {
e.printStackTrace();
}
//Log.d("This will be my result",result);
}

How to parse login response in android?

I am confused about parsing so I want to know about how to parse. Whenever I login with valid login id and password give response
{
"data": {
"status": "1",
"Full Name": [
{
"user_id": 1,
"user_name": "deepika#soms.in",
"full_name": "",
"display_name": "",
"token": "",
"photo_url": "http://clients.vfactor.in/putt2gether/images/profile/default.jpg"
}
],
"Event": [
{
"latest_event_id": "",
"format_id": ""
}
],
"msg": "Success Login"
}
}
and if invalid login id then give response
{
"Error": {
"msg": "Please Enter valid Email Address"
}
try {
JSONObject obj = new JSONObject(response);
if (obj.has("Error")) {
JSONObject objError = obj.getJSONObject("Error");
} else if (obj.has("data")) {
JSONObject objData = obj.getJSONObject("data");
}
} catch (Exception e) {
e.printStackTrace();
}
You need to parse the json answer.
There are many sources to learn how to do that:
Oracle documentation
Jackson documentation - Jackson is a library to parse json
GSon documentation - Another json parser
Let's assume response be,
String response;
try
{
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("data"))
{
JSONObject jsonObjData = jsonObject.getJSONObject("data");
String status = jsonObject.getString("status");
JSONArray jsonArrayName = jsonObjData.getJSONArray("Full Name");
for (int i = 0; i < jsonArrayName.length(); i++) {
JSONObject jsonObj = jsonArrayName.getJSONObject(i);
Integer user_id = jsonObj.getInt("user_id");
String user_name = jsonObj.getString("user_name");
String full_name = jsonObj.getString("full_name");
String display_name = jsonObj.getString("display_name");
String photo_url = jsonObj.getString("photo_url");
}
JSONArray jsonArrayEvent = jsonObjData.getJSONArray("Event");
for (int i = 0; i < jsonArrayEvent.length(); i++) {
JSONObject jsonObj = jsonArrayEvent.getJSONObject(i);
String latest_event_id = jsonObj.getString("latest_event_id");
String format_id = jsonObj.getString("format_id");
}
String msg = jsonObject.getString("msg");
} else if (jsonObject.has("Error")) {
JSONObject jsonObjError = jsonObject.getJSONObject("Error");
String msg = jsonObjError.getString("msg");
}
} catch (Exception e) {
e.printStackTrace();
}

Issues with JSON Parsing Android

I have Json like this:
{
"id": 226112,
"name": "name",
"min": 1,
"km": "0.33",
"url": "5___2_2.htm",
"departures": [
{
"type": "DATA",
"departures": {
"5": [
"04",
"19",
"34",
"47",
"59"
],
"6": [
"11",
"23",
"35",
"47",
"59"
]
etc..
And I try to parse it:
private static final String TAG_DEPARTURES = "departures";
private static final String TAG_TYPE = "type";
private static final String TAG_DEPARTURES2 = "departures";
private static String TAG_HOUR = "5";
...
example
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
timetables = jsonObj.getJSONArray(TAG_DEPARTURES);
for (int i = 0; i < timetables.length(); i++) {
JSONObject c = timetables.getJSONObject(i);
String type = c.getString(TAG_TYPE);
JSONObject departures = c.getJSONObject(TAG_DEPARTURES2);
String hour = departures.getString(TAG_HOUR);
HashMap<String, String> timetable = new HashMap<String, String>();
timetable.put(TAG_TYPE, type);
timetable.put(TAG_DEPARTURES2, hour);
timetableList.add(timetable);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
...
Finally I get this:
DATA ["04","19","34","47","59"]
And this is String
["04","19","34","47","59"]
I would like to get String[] tab, where:
tab[0] = "04";
tab[1] = "19";
...
I think your json returned is not like you want.maybe you want an array for the key:5,6,but your json showed in question is just a string,so if you can control the json returned by server,please change its format to an string array.
If you can't control the json returned,you should extract the real string by yourself.Like this:
public String[] extractArray(final String str){
final String strNoBrace = str.substring(1,str.length()-1);
String[] tempResult = strNoBrace.split(",");
if(tempResult==null) return null;
String[] result = new String[tempResult.size()];
for(int i=0,size=tempResult.size();i<size;++i){
String temp = tempResult[i];
result[i] = temp.substring(1,temp.length()-1);
}
return result;
}

JSONArray getValue

i have a teams.json file with following content
{
"league": "Champions League",
"season": "2015/16",
"start": "2015-11-01",
"end": "2016-03-31",
"teams": [
{ "name": "Spain" },
{ "name": "Germany"},
{ "name": "Italy" },
{ "name": "Brasil" },
{ "name": "Argentina" }
]
}
and i have JSONArray which works fine
JSONObject jsonObject = (JSONObject) obj;
JSONArray teamList = (JSONArray) jsonObject.get("teams");
Iterator<JSONArray> iterator = teamList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Output:
{"name":"Spain"}
{"name":"Germany"}
{"name":"Italy"}
{"name":"Brasil"}
{"name":"Argentina"}
But i just want the values in the Array without the {"name": ... stuff,
like
Spain, Germany,Italy,Brasil,Argentina
You can do this :
package foo.bar;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSON {
public static void main(String[] args) {
String str = "{\r\n\"league\": \"Champions League\",\r\n\"season\": \"2015/16\",\r\n\"start\": \"2015-11-01\",\r\n\"end\": \"2016-03-31\",\r\n\"teams\": [ \r\n { \"name\": \"Spain\" },\r\n { \"name\": \"Germany\"},\r\n { \"name\": \"Italy\" },\r\n { \"name\": \"Brasil\" },\r\n { \"name\": \"Argentina\" }\r\n]}";
JSONObject jsonObject = new JSONObject(str);
JSONArray teamList = (JSONArray) jsonObject.get("teams");
for (Object o : teamList) {
JSONObject team = (JSONObject) o;
System.out.println(team.getString("name"));
}
}
}
I hope it will help you..!
JSONArray teams=new JSONObject(jsondata).getJSONArray("teams");
for(int i=0;i<teams.length();i++){
JSONObject team=teams.getJSONObject(i);
System.out.println("value of name=="+team.getString("name"));
}
just create helper method for getting array.
package com.example.helloworld;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MyTest {
public static void main(String[] args) throws JSONException {
String str = "{'league': 'Champions League','season': '2015/16','start': '2015-11-01','end': '2016-03-31','teams': [ \r\n { 'name': 'Spain' },\r\n { 'name': 'Germany'},\r\n { 'name': 'Italy' },\r\n { 'name': 'Brasil' },\r\n { 'name': 'Argentina' }\r\n]}";
System.out.println(getCountyList(str).toString());
}
public static List<String> getCountyList(String json) throws JSONException {
List<String> list = new ArrayList<String>();
JSONObject jsonObject = new JSONObject(json);
JSONArray teamList = (JSONArray) jsonObject.get("teams");
for (int i = 0, len = teamList.length(); i < len; i++) {
JSONObject team = (JSONObject) teamList.get(i);
list.add((String) team.get("name"));
}
return list;
}
}

Categories

Resources