Related
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();
}
when receiving my json from my loop it comes as one big object
how do I prevent this can someone point me in the right direction or documents.
Log....
W/System.err: org.json.JSONException: Value {"1":{"id":1,"name":"Bitcoin","symbol":"BTC","website_slug":"bitcoin","rank":1,"circulating_supply":17153487,"total_supply":17153487,"max_supply":21000000,"quotes":{"USD":{"price":6720.93,"volume_24h":4367200000,"market_cap":115287385383,"percent_change_1h":-0.09,"percent_change_24h":2.07,"percent_change_7d":3.26}},"last_updated":1531828586},"1027":{"id":1027,"name":"Ethereum","symbol":"ETH","website_slug":"ethereum","rank":2,"circulating_supply":100744923,"total_supply":100744923,"max_supply":null,"quotes":{"USD":{"price":472.777,"volume_24h":1774520000,"market_cap":47629882298,"percent_change_1h":-0.45,"percent_change_24h":0.3,"percent_change_7d":5.32}},"last_updated":1531828591},"52":{"id":52,"name":"XRP","symbol":"XRP","website_slug":"ripple","rank":3,"circulating_supply":39262444717,"total_supply":99991916481,"max_supply":100000000000,"quotes":{"USD":{"price":0.473278,"volume_24h":269811000,"market_cap":18582051311,"percent_change_1h":-0.18,"percent_change_24h":2.43,"percent_change_7d":4.17}},"last_updated":1531828571},"1831":{"id":1831,"name":"Bitcoin Cash","symbol":"BCH","website_slug":"bitcoin-cash","rank":4,"circulating_supply":17242013,"total_supply":17242013,"max_supply":21000000,"quotes":{"USD":{"price":793.963,"volume_24h":471637000,"market_cap":13689519971,"percent_change_1h":-0.47,"percent_change_24h":3.58,"percent_change_7d":12.07}},"last_updated":1531828592},"1765":{"id":1765,"name":"EOS","symbol":"EOS","website_slug":"eos","rank":5,"circulating_supply":896149492,"total_supply":900000000,"max_supply":1000000000,"quotes":{"USD":{"price":7.94815,"volume_24h":666448000,"market_cap":7122730586,"percent_change_1h":-0.29,"percent_change_24h":2.5,"percent_change_7d":6.31}},"last_updated":1531828590},"2":{"id":2,"name":"Litecoin","symbol":"LTC","website_slug":"litecoin","rank":6,"circulating_supply":57444758,"total_supply":57444758,"max_supply":84000000,"quotes":{"USD":{"price":83.7447,"volume_24h":283495000,"market_cap":4810693998,"percent_change_1h":-0.17,"percent_change_24h":1.63,"percent_change_7d":8.91}},"last_updated":1531828567},"512":{"id":512,"name":"Stellar","symbol":"XLM","website_slug":"stellar","rank":7,"circulating_supply":18766530971,"total_supply":104125061584,"max_supply":null,"quotes":{"USD":{"price":0.231804,"volume_24h":49352700,"market_cap":4350156945,"percent_change_1h":-0.94,"percent_change_24h":0.8,"percent_change_7d":17.92}},"last_updated":1531828584},"2010":{"id":2010,"name":"Cardano","symbol":"ADA","website_slug":"cardano","rank":8,"circulating_supply":25927070538,"total_supply":31112483745,"max_supply":45000000000,"quotes":{"USD":{"price":0.152682,"volume_24h":86195700,"market_cap":3958596984,"percent_change_1h":0.16,"percent_change_24h":1.2,"percent_change_7d":15.48}},"last_updated":1531828594},"1720":{"id":1720,"name":"IOTA","symbol":"MIOTA","website_slug":"iota","rank":9,"circulating_supply":2779530283,"total_supply":2779530283,"max_supply":2779530283,"quotes":{"USD":{"price":1.06608,"volume_24h":45845200,"market_cap":2963201644,"percent_change_1h":-0.49,"percent_change_24h":0.44,"percent_change_7d":8.21}},"last_updated":1531828590},"825":{"id":825,"name":"Tether","symbol":"USDT","website_slug":"tether","rank":10,"circulating_supply":2707140346,"total_supply":3080109502,"max_supply":null,"quotes":{"USD":{"price":1.00215,"volume_24h":2728850000,"market_cap":2712960697,"percent_change_1h":0.11,"percent_change_24h":0.45,"percent_change_7d":-0.16}},"last_updated":1531828588},"1958":{"id":1958,"name":"TRON","symbol":"TRX","website_slug":"tron","rank":11,"circulating_supply":65748111645,"total_supply":99000000000,"max_supply":null,"quotes":{"USD":{"price":0.0367706,"volume_24h":191259000,"market_cap":2417597514,"percent_change_1h":0.03,"percent_change_24h":1.55,"percent_change_7d":8.49}},"last_updated":1531828593},"1376":{"id":1376,"name":"NEO","symbol":"NEO","website_slug":"neo","rank":12,"circulating_supply":65000000,"total_supply":100000000,"max_supply":100000000,"quotes":{"USD":{"price":36.2949,"volume_24h":128189
here is my code for the request
public ArrayList getCoin () {
firstlist.clear();
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
Constants.URL_JSON, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray coinArray = response.getJSONArray("data");
for (int i = 0; i < coinArray.length(); i++) {
JSONObject coinOBJ = coinArray.getJSONObject(i);
CoinMarketAPI coin = new CoinMarketAPI();
// coin.setId(coinOBJ.getString("id"));
//coin.setName(coinOBJ.getString("name"));
//coin.setSymbol(coinOBJ.getString("symbol"));
//coin.setWebsite_slug(coinOBJ.getString("website_slug"));
// coin.setRank(coinOBJ.getString("rank"));
// coin.setCirculating_supply(coinOBJ.getString("circulating_supply"));
// coin.setTotal_supply(coinOBJ.getString("total_supply"));
// coin.setQuotes(coinOBJ.getString("quotes"));
// coin.setUSD(coinOBJ.getString("USD"));
// coin.setPrice(coinOBJ.getString("price"));
Log.d(TAG, coin.getName());
firstlist.add(coin);
}
JSON
{
"data": {
"1": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17008162.0,
"total_supply": 17008162.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 9024.09,
"volume_24h": 8765400000.0,
"market_cap": 153483184623.0,
"percent_change_1h": -2.31,
"percent_change_24h": -4.18,
"percent_change_7d": -0.47
}
},
"last_updated": 1525137271
},
"1027": {
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"website_slug": "ethereum",
"rank": 2,
"circulating_supply": 99151888.0,
"total_supply": 99151888.0,
"max_supply": null,
"quotes": {
"USD": {
"price": 642.399,
"volume_24h": 2871290000.0,
"market_cap": 63695073558.0,
"percent_change_1h": -3.75,
"percent_change_24h": -7.01,
"percent_change_7d": -2.32
}
},
NOTE some lines are commented out to prevent further errors.
Im think the error is to do the jsonarray response line but not to sure how to fix it. any help will be greatly appreciated.
data is object, not an array, so you can loop by iterator like this
JSONObject coinArray = response.getJSONObject("data");
Iterator<String> iter = coinArray.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object coinOBJ = coinArray.get(key);
CoinMarketAPI coin = new CoinMarketAPI();
coin.setId(coinOBJ.getString("id"));
coin.setName(coinOBJ.getString("name"));
coin.setSymbol(coinOBJ.getString("symbol"));
coin.setWebsite_slug(coinOBJ.getString("website_slug"));
coin.setRank(Integer.parseInt(coinOBJ.getString("rank")));
coin.setCirculating_supply(coinOBJ.getString("circulating_supply"));
coin.setTotal_supply(coinOBJ.getString("total_supply"));
coin.setQuotes(coinOBJ.getString("quotes"));
coin.setUSD(coinOBJ.getString("USD"));
coin.setPrice(coinOBJ.getString("price"));
Log.d(TAG, coin.getName());
firstlist.add(coin);
} catch (JSONException e) {
// Something went wrong!
}
}
Let me explain it for you. What I did is that "data" was a JsonObject and has multiple objects Inside itself. so I converted data Into Json array by jsonObject.names(); Now I will get each object inside data through for loop.
JSONObject jsonObject = response.getJSONObject("data");
JSONArray jsonArray = jsonObject.names();
Log.e(tag,jsonArray.toString());
for(int i=0;i<jsonArray.length();i++){
JSONObject getObjectFromJsonArray=jsonObject.getJSONObject(jsonArray.getString(i));
CoinMarketAPI coin=new CoinMarketAPI();
coin.setId(getObjectFromJsonArray.getString("id"));
coin.setName(getObjectFromJsonArray.getString("name"));
coin.setSymbol(getObjectFromJsonArray.getString("symbol"));
coin.setWebsite_slug(getObjectFromJsonArray.getString("website_slug"));
coin.setRank(getObjectFromJsonArray.getString("rank"));
coin.setCirculating_supply(getObjectFromJsonArray.getString("circulating_supply"));
coin.setTotal_supply(getObjectFromJsonArray.getString("total_supply"));
JSONObject qoutes = getObjectFromJsonArray.getJSONObject("quotes");
JSONObject USD = qoutes.getJSONObject("USD");
coin.setPrice(USD.getString("price"));
firstlist.add(coin);
}
I have an android app (Java) that processes an API from te web.
Currently the app is processing a JSON file that looks like this:
{
"contacts": [
{
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890"
},
{
"id": 2,
ETC...
I need to process another JSON file but it has a different structure:
{
"contacts": {
"1": {
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890",
"level1": {
"level2": {
"level3": 3,
}
},
"last_updated": 20180712
},
"2": {
ETC...
How do I process this second JSON file by adjusting the below code?
if (jsonSource != null) {
try {
JSONObject jsonObject = new JSONObject(jsonSource);
JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject contacts = jsonArrayData.getJSONObject(i);
String id = contacts.getString("id");
String name = contacts.getString("name");
String email = contacts.getString("email");
String phone = contacts.getString("phone");
HashMap<String, String> values = new HashMap<>();
values.put("id", id);
values.put("name", name);
values.put("email, email);
values.put("phone, phone);
contactList.add(values);
}
} catch (final JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Unable to retrieve JSON file from URL");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
return null;
Any help is much appreciated!
It looks, that inside first json you have "contacts" as array of objects, and inside second one you have "contacts" as object. Inside it you have other objects, simplified version looks like this:
"contacts": [
{...},
{...},
{...}
]
"contacts": {
"1": {...},
"2": {...},
"3": {...}
}
So, the only option you have is to check manually is "contacts" array or object, and based on it change your code.
It would look like this:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
JSONObject contactsJson = jsonObject.getJSONObject("contacts");
for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
String key = it.next();
JSONObject contactJson = contactsJson.getJSONObject(key);
// your code to process contact item
}
} else {
// Your code to process every contact item
}
I'm currently developing a physics app that is supposed to show a list of formulas and even solve some of them (the only problem is the ListView)
This is my main layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:measureWithLargestChild="false"
android:orientation="vertical"
tools:context=".CatList">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/titlebar">
<TextView
android:id="#+id/Title1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ff1c00"
android:textIsSelectable="false" />
</RelativeLayout>
<ListView
android:id="#+id/listFormulas"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
And this is my main activity
package com.wildsushii.quickphysics;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.view.Menu;
import android.widget.ListView;
public class CatList extends Activity {
public static String AssetJSONFile(String filename, Context context) throws IOException {
AssetManager manager = context.getAssets();
InputStream file = manager.open(filename);
byte[] formArray = new byte[file.available()];
file.read(formArray);
file.close();
return new String(formArray);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cat_list);
ListView categoriesL = (ListView) findViewById(R.id.listFormulas);
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
Context context = null;
try {
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject formArray = (new JSONObject()).getJSONObject("formules");
String formule = formArray.getString("formule");
String url = formArray.getString("url");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
//My problem is here!!
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cat_list, menu);
return true;
}
}
I actually know I can make this without using JSON but I need more practice parsing JSON. By the way, this is the JSON
{
"formules": [
{
"formule": "Linear Motion",
"url": "qp1"
},
{
"formule": "Constant Acceleration Motion",
"url": "qp2"
},
{
"formule": "Projectile Motion",
"url": "qp3"
},
{
"formule": "Force",
"url": "qp4"
},
{
"formule": "Work, Power, Energy",
"url": "qp5"
},
{
"formule": "Rotary Motion",
"url": "qp6"
},
{
"formule": "Harmonic Motion",
"url": "qp7"
},
{
"formule": "Gravity",
"url": "qp8"
},
{
"formule": "Lateral and Longitudinal Waves",
"url": "qp9"
},
{
"formule": "Sound Waves",
"url": "qp10"
},
{
"formule": "Electrostatics",
"url": "qp11"
},
{
"formule": "Direct Current",
"url": "qp12"
},
{
"formule": "Magnetic Field",
"url": "qp13"
},
{
"formule": "Alternating Current",
"url": "qp14"
},
{
"formule": "Thermodynamics",
"url": "qp15"
},
{
"formule": "Hydrogen Atom",
"url": "qp16"
},
{
"formule": "Optics",
"url": "qp17"
},
{
"formule": "Modern Physics",
"url": "qp18"
},
{
"formule": "Hydrostatics",
"url": "qp19"
},
{
"formule": "Astronomy",
"url": "qp20"
}
]
}
I have tried a lot of things and even delete the entire project to make a new one :(
As Faizan describes in their answer here:
First of all read the Json File from your assests file using below code.
and then you can simply read this string return by this function as
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and use this method like that
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("formules");
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
Log.d("Details-->", jo_inside.getString("formule"));
String formula_value = jo_inside.getString("formule");
String url_value = jo_inside.getString("url");
//Add your values in your `ArrayList` as below:
m_li = new HashMap<String, String>();
m_li.put("formule", formula_value);
m_li.put("url", url_value);
formList.add(m_li);
}
} catch (JSONException e) {
e.printStackTrace();
}
For further details regarding JSON Read HERE
With Kotlin have this extension function to read the file return as string.
fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}
Parse the output string using any JSON parser.
{ // json object node
"formules": [ // json array formules
{ // json object
"formule": "Linear Motion", // string
"url": "qp1"
}
What you are doing
Context context = null; // context is null
try {
String jsonLocation = AssetJSONFile("formules.json", context);
So change to
try {
String jsonLocation = AssetJSONFile("formules.json", CatList.this);
To parse
I believe you get the string from the assests folder.
try
{
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject jsonobject = new JSONObject(jsonLocation);
JSONArray jarray = (JSONArray) jsonobject.getJSONArray("formules");
for(int i=0;i<jarray.length();i++)
{
JSONObject jb =(JSONObject) jarray.get(i);
String formula = jb.getString("formule");
String url = jb.getString("url");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Just summarising #libing's answer with a sample that worked for me.
val gson = Gson()
val todoItem: TodoItem = gson.fromJson(this.assets.readAssetsFile("versus.json"), TodoItem::class.java)
private fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}
Without this extension function the same can be achieved by using BufferedReader and InputStreamReader this way:
val i: InputStream = this.assets.open("versus.json")
val br = BufferedReader(InputStreamReader(i))
val todoItem: TodoItem = gson.fromJson(br, TodoItem::class.java)
Method to read JSON file from Assets folder and return as a string object.
public static String getAssetJsonData(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("myJson.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
Log.e("data", json);
return json;
}
Now for parsing data in your activity:-
String data = getAssetJsonData(getApplicationContext());
Type type = new TypeToken<Your Data model>() {
}.getType();
<Your Data model> modelObject = new Gson().fromJson(data, type);
If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this. In our case we use applicationContext.
So in Utility class you can define all extension functions.
Utility.kt
fun Context.loadJSONFromAssets(fileName: String): String {
return applicationContext.assets.open(fileName).bufferedReader().use { reader ->
reader.readText()
}
}
MainActivity.kt
You can define private function for load JSON data from assert like this:
lateinit var facilityModelList: ArrayList<FacilityModel>
private fun bindJSONDataInFacilityList() {
facilityModelList = ArrayList<FacilityModel>()
val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
for (i in 0 until facilityJsonArray.length()){
val facilityModel = FacilityModel()
val facilityJSONObject = facilityJsonArray.getJSONObject(i)
facilityModel.Facility = facilityJSONObject.getString("Facility")
facilityModel.District = facilityJSONObject.getString("District")
facilityModel.Province = facilityJSONObject.getString("Province")
facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
facilityModel.code = facilityJSONObject.getInt("code")
facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")
facilityModelList.add(facilityModel)
}
}
You have to pass facilityModelList in your ListView
FacilityModel.kt
class FacilityModel: Serializable {
var District: String = ""
var Facility: String = ""
var Province: String = ""
var Subdistrict: String = ""
var code: Int = 0
var gps_latitude: Double= 0.0
var gps_longitude: Double= 0.0
}
In my case JSON response start with JSONArray
[
{
"code": 875933,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Amabele Clinic",
"gps_latitude": -32.6634,
"gps_longitude": 27.5239
},
{
"code": 455242,
"Province": "Eastern Cape",
"District": "Amathole DM",
"Subdistrict": "Amahlathi LM",
"Facility": "Burnshill Clinic",
"gps_latitude": -32.7686,
"gps_longitude": 27.055
}
]
Using OKIO
implementation("com.squareup.okio:okio:3.0.0-alpha.4")
With Java:
public static String readJsonFromAssets(Context context, String filePath) {
try {
InputStream input = context.getAssets().open(filePath);
BufferedSource source = Okio.buffer(Okio.source(input));
return source.readByteString().string(Charset.forName("utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
With Kotlin:
fun readJsonFromAssets(context: Context, filePath: String): String? {
try {
val source = context.assets.open(filePath).source().buffer()
return source.readByteString().string(Charset.forName("utf-8"))
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
and then...
String data = readJsonFromAssets(context, "json/some.json"); //here is my file inside the folder assets/json/some.json
Type reviewType = new TypeToken<List<Object>>() {}.getType();
if (data != null) {
Object object = new Gson().fromJson(data, reviewType);
}
Source code How to fetch Local Json from Assets folder
https://drive.google.com/open?id=1NG1amTVWPNViim_caBr8eeB4zczTDK2p
{
"responseCode": "200",
"responseMessage": "Recode Fetch Successfully!",
"responseTime": "10:22",
"employeesList": [
{
"empId": "1",
"empName": "Keshav",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "9654267338",
"empDesignation": "Sr. Java Developer",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "2",
"empName": "Ram",
"empFatherName": "Mr Dasrath ji",
"empSalary": "9999999999",
"empDesignation": "Sr. Java Developer",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "3",
"empName": "Manisha",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "8826420999",
"empDesignation": "BusinessMan",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "4",
"empName": "Happy",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "9582401701",
"empDesignation": "Two Wheeler",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "5",
"empName": "Ritu",
"empFatherName": "Mr Keshav Gera",
"empSalary": "8888888888",
"empDesignation": "Sararat Vibhag",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
}
]
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee);
emp_recycler_view = (RecyclerView) findViewById(R.id.emp_recycler_view);
emp_recycler_view.setLayoutManager(new LinearLayoutManager(EmployeeActivity.this,
LinearLayoutManager.VERTICAL, false));
emp_recycler_view.setItemAnimator(new DefaultItemAnimator());
employeeAdapter = new EmployeeAdapter(EmployeeActivity.this , employeeModelArrayList);
emp_recycler_view.setAdapter(employeeAdapter);
getJsonFileFromLocally();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = EmployeeActivity.this.getAssets().open("employees.json"); //TODO Json File name from assets folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void getJsonFileFromLocally() {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
String responseCode = jsonObject.getString("responseCode");
String responseMessage = jsonObject.getString("responseMessage");
String responseTime = jsonObject.getString("responseTime");
Log.e("keshav", "responseCode -->" + responseCode);
Log.e("keshav", "responseMessage -->" + responseMessage);
Log.e("keshav", "responseTime -->" + responseTime);
if(responseCode.equals("200")){
}else{
Toast.makeText(this, "No Receord Found ", Toast.LENGTH_SHORT).show();
}
JSONArray jsonArray = jsonObject.getJSONArray("employeesList"); //TODO pass array object name
Log.e("keshav", "m_jArry -->" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
{
EmployeeModel employeeModel = new EmployeeModel();
JSONObject jsonObjectEmployee = jsonArray.getJSONObject(i);
String empId = jsonObjectEmployee.getString("empId");
String empName = jsonObjectEmployee.getString("empName");
String empDesignation = jsonObjectEmployee.getString("empDesignation");
String empSalary = jsonObjectEmployee.getString("empSalary");
String empFatherName = jsonObjectEmployee.getString("empFatherName");
employeeModel.setEmpId(""+empId);
employeeModel.setEmpName(""+empName);
employeeModel.setEmpDesignation(""+empDesignation);
employeeModel.setEmpSalary(""+empSalary);
employeeModel.setEmpFatherNamer(""+empFatherName);
employeeModelArrayList.add(employeeModel);
} // for
if(employeeModelArrayList!=null) {
employeeAdapter.dataChanged(employeeModelArrayList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You have to write a function to read the Json File from your assests folder.
public String loadJSONFile() {
String json = null;
try {
InputStream inputStream = getAssets().open("yourfilename.json");
int size = inputStream.available();
byte[] byteArray = new byte[size];
inputStream.read(byteArray);
inputStream.close();
json = new String(byteArray, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
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 .