Issues with JSON Parsing Android - java

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;
}

Related

How to display items from JSON file to spinner

I am trying to display a list on a spinner from a json file in asset folder. I found a tutorial but I think my format is wrong, please help!
also, will this process take time to load to the spinner if the list has up to 300 items?
here is my main activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayList<String> items = getFood("food.json");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, items);
spinner.setAdapter(adapter);
}
public ArrayList<String> getBanks(String fileName) {
JSONObject jsonObject = null;
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
jsonObject = new JSONObject(json);
if (jsonObject != null) {
for (int i = 0; i < jsonObject.length(); i++) {
JSONArray foodList = jsonObject.getJSONArray("data");
if(cList != null){
for(int j=0; i<cList.length(); j++){
JSONObject fList = foodList.getJSONObject(j);
String food_name = foodList.getString("name");
String food_code = foodList.getString("code");
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException je) {
je.printStackTrace();
}
return cList;
}
}
the structure of my response, saved as food.json
{
"status": "Successful",
"data": [
{
"code": "11",
"id": 1,
"name": "Apple"
},
{
"code": "22",
"id": 2,
"name": "Carrot"
},
{
"code": "33",
"id": 3,
"name": "Diamonds"
},
{
"code": " 44",
"id": 4,
"name": "Eggs"
},
{
"code": "55",
"id": 5,
"name": "Fish"
}
],
"message": "Action was successful"
}
For this task use jackson-jr (Size is very small and faster than other libraries like Gson, Jasckson core ...)
Considering Performance, it is the best option than other.
Now let's go to the solution
First import jackson-jr library to Your android project
implementation 'com.fasterxml.jackson.jr:jackson-jr-objects:2.10.0'
then create two model classes like this
public class Food {
private String status;
private List<Data> data;
private String message;
public Food() {
}
//getters and setters
}
public class Data {
private String code;
private int id;
private String name;
public Data() {
}
//getters and setters
}
Final step get data objects
import com.fasterxml.jackson.jr.ob.JSON;
private List<Data> getData() {
List<Data> data = null;
try {
// give your json file as a inputstream
//InputStream is = getResources().openRawResource(R.raw.food);
InputStream is = getResources().getAssets().open("food.json");
Food bean = JSON.std.beanFrom(Food.class, is);
data = bean.getData();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
You can do whatever after that using this list of Data...
For passing only food names
There are a lot of ways. Here is a simple way
in your onCreate method use below code
List<Data> data = getData();
List<String> foodNames = getFoodNamesFromData(data);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, foodNames);
// Your usual codes
and here is the getFoodNamesFromData() method
private List<String> getFoodNamesFromData(List<Data> dataList) {
List<String> foodNames = new ArrayList<>();
for(Data data :dataList){
String foodName = data.getName();
foodNames.add(foodName);
}
return foodNames;
}
Happy coding!!!
Why don't you create a custom class for following structure
{
"code": "11",
"id": 1,
"name": "Apple"
}
So that you can use GSON library to parse json into a list using TypeToken and it'll be easy to pass to a adapter.
You can do like,
List<YourClass> yourClass = Gson().fromJson(json.toString(),new TypeToken<List<YourClass>>(){}.getType())

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 work with json object and jsonarray

I have this JSON response:
"objects":{
"5": [
[
{
"id_lot_espace": 0,
"id_lot_objet": "0",
"id_objet_piece": 0,
"params": {
"auto": "1",
"objLink": "0",
"setpointM": "7",
"setpoint0": "21",
"setpoint1": "19",
"setpointA": "16",
"tempSocialJ": "19",
"tempSocialN": "17",
"tempMin": "7",
"tempMax": "30",
"tempFrom": "2018-10-15",
"tempTo": "2019-04-15"
},
"label": "migo",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "zwave_device_fab36177_node6_thermostat_setpoint_heating",
"renommable": "0",
"id_famille": 5,
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
]
],
"17": {
"381": {
"19": {
"id_lot_espace": "381",
"id_lot_objet": "0",
"id_objet_piece": "19",
"params": "",
"label": "Pièce principale - Tête thermostatique",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "",
"renommable": "0",
"id_famille": "17",
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
}
}
}
}
I want to access pieceLabel in each element. Here’s what I’ve tried so far:
job = new JSONObject(responseContent);
JSONObject object = job.getJSONObject("objects");
Iterator<String> it = object.keys();
while (it.hasNext()) {
String key = it.next();
JSONObject obj1 = object.getJSONObject(key);
Iterator<String> it1 = obj1.keys();
while (it1.hasNext()) {
String key1 = it1.next();
JSONObject obj2 = obj1.getJSONObject(key1);
Iterator<String> it2 = obj2.keys();
while (it2.hasNext()) {
String key2 = it2.next();
final JSONObject obj3 = obj2.getJSONObject(key2);
String pieceLabel = String.valueOf(obj3.get("pieceLabel"));
}
}
}
Please check your json its having issue. You can use many tools online to check your json if its proper or not.
I usually use https://codebeautify.org/jsonviewer
Corrected Json
[
[
{
"id_lot_espace": 0,
"id_lot_objet": "0",
"id_objet_piece": 0,
"params": {
"auto": "1",
"objLink": "0",
"setpointM": "7",
"setpoint0": "21",
"setpoint1": "19",
"setpointA": "16",
"tempSocialJ": "19",
"tempSocialN": "17",
"tempMin": "7",
"tempMax": "30",
"tempFrom": "2018-10-15",
"tempTo": "2019-04-15"
},
"label": "migo",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "zwave_device_fab36177_node6_thermostat_setpoint_heating",
"renommable": "0",
"id_famille": 5,
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
]
]
{
"17": {
"381": {
"19": {
"id_lot_espace": "381",
"id_lot_objet": "0",
"id_objet_piece": "19",
"params": "",
"label": "Pièce principale - Tête thermostatique",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "",
"renommable": "0",
"id_famille": "17",
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
}
}
}
Final Code
try {
JSONObject jObject = new JSONObject(sss.trim());
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
Log.d("vt","output1 "+key);
JSONObject obj1 = jObject.getJSONObject(key);
Iterator<String> it1 = obj1.keys();
while (it1.hasNext()) {
String key1 = it1.next();
Log.d("vt","output2 "+key1);
JSONObject obj2 = obj1.getJSONObject(key1);
Iterator<String> it2 = obj2.keys();
while (it2.hasNext()) {
String key2 = it2.next();
Log.d("vt","output3 "+key2);
final JSONObject obj3 = obj2.getJSONObject(key2);
String pieceLabel = String.valueOf(obj3.get("pieceLabel"));
Log.d("vt","final "+pieceLabel);
}
}
}
}catch (Exception e){
Log.d("vt","error "+e.getMessage());
}
You need to iterate your unstructured json recursively and check every key.
Here is a working example to show you how to achieve what you want to do:
public class Main {
private static List<String> values = new ArrayList();
public static void main(String[] args) {
try {
JSONObject jsonObject = new JSONObject(new String(Files.readAllBytes(Paths.get("test.json"))));
findValues(jsonObject);
values.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void findValues(Object root) {
if (root instanceof JSONObject) {
Iterator<String> keys = ((JSONObject)root).keys();
while (keys.hasNext()) {
String key = keys.next();
if ("pieceLabel".equals(key)) {
values.add(((JSONObject)root).getString(key));
}
else {
Object o = ((JSONObject)root).get(key);
findValues(o);
}
}
}
else if (root instanceof JSONArray) {
for (Object o : (JSONArray)root) {
findValues(o);
}
}
}
}
test.json file contains your example json.
Output is :
Pièce principale
Pièce principale
Change the values and order of keys and see the result.
I passed your json through https://jsoneditoronline.org and did not find any error.
I used json-simple which can be found here:
https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1
My example is below with no loops.
public static void main( String[] args ) {
JSONParser parser = new JSONParser();
JSONObject jobj = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(".json"),"UTF-8"));
jobj = (JSONObject) parser.parse(reader);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
JSONObject jobj2 = (JSONObject) jobj.get("object"); // outer object.
JSONObject jobj3 = (JSONObject) jobj2.get("17"); // nested object.
JSONObject jobj4 = (JSONObject) jobj3.get("381"); // nested object.
JSONObject jobj5 = (JSONObject) jobj4.get("19"); // nested object.
System.out.println(jobj5.get("pieceLabel")); // Returns the value to where the specified key is mapped.
JSONArray jsarry = (JSONArray) jobj.get("5"); // Json Array.
JSONArray jsarry2 = (JSONArray) jsarry.get(0); // nested Json Array.
JSONObject nestedjsobj = (JSONObject) jsarry2.get(0); // nested object.
System.out.println(nestedjsobj.get("pieceLabel")); // Returns the value to where the specified key is mapped.
}
output:
Pièce principale
Pièce principale

org.json.JSONException: No value for price

I get result json and parse in android. Exception has happened with a message: org.json.JSONException: No value for price
W/System.err: org.json.JSONException: No value for price
W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
W/System.err: at org.json.JSONObject.getString(JSONObject.java:550)
My java class
JSONParser jsonParser = new JSONParser();
// tracks JSONArray
JSONArray albums = null;
// Album id
String album_id = null;
String song_id = null;
String album_name, song_name, price;
// single song JSON url
// GET parameters album, song
private static final String URL_SONG = "my url";
// ALL JSON node names
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_ALBUM = "name"; // album
...
try {
JSONObject jObj = new JSONObject(json);
if(jObj != null){
song_name = jObj.getString(TAG_NAME);
album_name = jObj.getString(TAG_ALBUM);
price = jObj.getString(TAG_PRICE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
My json URL:
{
"id": "551"
"name": "Rent Disk"
"price": "3233333"
"album_id": "3"
"album": "Michael"
}
How to fix this exception? thank so much !!
You can put a check like this before putting value
JSONObject jObj = new JSONObject(json);
if(jObj != null) {
if(jObj.has(TAG_NAME)) {
song_name = jObj.getString(TAG_NAME);
}
if(jObj.has(TAG_ALBUM)){
album_name = jObj.getString(TAG_ALBUM);
}
if(jObj.has(TAG_PRICE)){
price = jObj.getString(TAG_PRICE);
}
}
JSONException
Thrown to indicate a problem with the JSON API
FYI
{
"id": "551"
"name": "Rent Disk"
"price": "3233333"
"album_id": "3"
"album": "Michael"
}
Post your Json Here
If above is your json then it is not valid .
For your requirement you should use JSONObject .has("") and .isNull("") method .
Edited
Your perfect Json is
{ "id": 551, "name": "Cho thue xe Toyota5", "price": "3233333", "album_id": "3", "album": "Huyndai" }
Try with this
JSONObject myJson = new JSONObject(json);
String getName = myJson.optString("name");
int getID= myJson.optInt("id");

Convert string to JSON array

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 .

Categories

Resources