Cannot to be cast json - java

I am very new to json and I made an example below,
also trying to parse it in a good way though I face issues
I am using Eclipse with:
JRE System Library[Java1.8] and using library:
json-simple-1.1.1.jar
I have made following JSON file:
[
[
{
"TestScenario_1": {
"Transaction": "A",
"description": "This is a test A",
"Co-no": "",
"Project": "Proj1"
}
}
],
[
{
"TestScenario_2": {
"Transaction": "B",
"description": "This is a test B",
"Co-no": "",
"Project": "Proj2"
}
}
]
]
Here is my script that try to read the file
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParseTest {
private static final String filePath = "C:\\temp\\mytest2.json";
#SuppressWarnings({ "unchecked", "unused", "rawtypes" })
public static void main(String[] args) {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jo = (JSONObject) jsonParser.parse(reader);
// get a String from the JSON object
Long TestScenario=(Long) jo.get("TestScenario");
System.out.println("TestScenario " + TestScenario);
String Transaction=(String) jo.get("Transaction");
System.out.println("Transaction " + Transaction);
String Description=(String) jo.get("Description");
System.out.println("Description " + Description);
String Cono=(String) jo.get("Co-no");
System.out.println("Co-no " + Cono);
JSONArray Parameters= (JSONArray) jo.get("Parameters");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}
though i get following error:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at JsonParseTest.main(JsonParseTest.java:25)
Could someone help me out?
Thank you in advance

One simple approach might be recursive method for the json string both a json array and object with a instanceof method in java.
So, two method needed, the one for json array
private static void searchJSONArray(JSONArray arry) {
JSONArray jarry = arry;
JSONObject jobj = null;
for (Iterator iter = jarry.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof JSONArray) {
searchJSONArray((JSONArray) o);
} else if (o instanceof JSONObject) {
jobj = (JSONObject) o;
Set keyset = jobj.keySet();
for (Iterator iter2 = keyset.iterator(); iter2.hasNext();) {
String key = (String) iter2.next();
Object value = jobj.get(key);
if(value instanceof JSONObject)
{
System.out.println("[" + key + "]");
searchJSONObject((JSONObject)value);
}
else
{
System.out.println(key + "=" + (String)value);
}
}
}
}
}
and another for json object.
private static void searchJSONObject(JSONObject obj) {
JSONObject jobj = obj;
Set keyset = jobj.keySet();
for (Iterator iter2 = keyset.iterator(); iter2.hasNext();) {
String key = (String) iter2.next();
Object value = jobj.get(key);
if(value instanceof JSONObject)
{
searchJSONObject((JSONObject)value);
}
else
{
System.out.println(key + "=" + (String)value);
}
}
}
Then, the full source is as follows;
package com.tobee.tests.parse.json;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParseTest {
private static final String filePath = "resource/aa/mytest2.json";
private static void searchJSONObject(JSONObject obj) {
JSONObject jobj = obj;
Set keyset = jobj.keySet();
for (Iterator iter2 = keyset.iterator(); iter2.hasNext();) {
String key = (String) iter2.next();
Object value = jobj.get(key);
if(value instanceof JSONObject)
{
searchJSONObject((JSONObject)value);
}
else
{
System.out.println(key + "=" + (String)value);
}
}
}
private static void searchJSONArray(JSONArray arry) {
JSONArray jarry = arry;
JSONObject jobj = null;
for (Iterator iter = jarry.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof JSONArray) {
searchJSONArray((JSONArray) o);
} else if (o instanceof JSONObject) {
jobj = (JSONObject) o;
Set keyset = jobj.keySet();
for (Iterator iter2 = keyset.iterator(); iter2.hasNext();) {
String key = (String) iter2.next();
Object value = jobj.get(key);
if(value instanceof JSONObject)
{
System.out.println("[" + key + "]");
searchJSONObject((JSONObject)value);
}
else
{
System.out.println(key + "=" + (String)value);
}
}
}
}
}
public static void main(String[] args) {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
Object jsonThing = jsonParser.parse(reader);
if (jsonThing instanceof JSONArray) {
searchJSONArray((JSONArray) jsonThing);
} else if (jsonThing instanceof JSONObject) {
JSONObject jobj = (JSONObject) jsonThing;
Set keyset = jobj.keySet();
for (Iterator iter2 = keyset.iterator(); iter2.hasNext();) {
String key = (String) iter2.next();
String value = (String) jobj.get(key);
System.out.println(key + "=" + value);
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
#SuppressWarnings({ "unchecked", "unused", "rawtypes" })
public static void your_main(String[] args) {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jo = (JSONObject) jsonParser.parse(reader);
// get a String from the JSON object
Long TestScenario = (Long) jo.get("TestScenario");
System.out.println("TestScenario " + TestScenario);
String Transaction = (String) jo.get("Transaction");
System.out.println("Transaction " + Transaction);
String Description = (String) jo.get("Description");
System.out.println("Description " + Description);
String Cono = (String) jo.get("Co-no");
System.out.println("Co-no " + Cono);
JSONArray Parameters = (JSONArray) jo.get("Parameters");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}
The output is here
[TestScenario_1]
Co-no=
Project=Proj1
Transaction=A
description=This is a test A
[TestScenario_2]
Co-no=
Project=Proj2
Transaction=B
description=This is a test B

Fix your json to:
[{
"Transaction": "A",
"Description": "This is a test A",
"Co-no": "",
"Project": "Proj1"
},
{
"Transaction": "B",
"Description": "This is a test B",
"Co-no": "",
"Project": "Proj2"
}]
And change your implementation with this:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Map;
public class JsonParseTest {
private static final String FILE_PATH = "C:\\temp\\mytest2.json";
public static void main(String[] args) {
try (InputStream source = Files.newInputStream(Paths.get(FILE_PATH), StandardOpenOption.READ)) {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// read the json file
List<Map> jo = mapper.readValue(source, List.class);
jo.forEach((elem) -> {
System.out.println("Transaction " + elem.get("Transaction"));
System.out.println("Description " + elem.get("Description"));
System.out.println("Co-no " + elem.get("Co-no"));
System.out.println("Project " + elem.get("Project"));
System.out.println("***************************************");
});
String jsonStr = mapper.writeValueAsString(jo);
System.out.println("Json content\n" + jsonStr);
} catch (IOException | NullPointerException ex) {
ex.printStackTrace();
}
}
}
And executing this, you will have this result:
Transaction A
Description This is a test A
Co-no
Project Proj1
***************************************
Transaction B
Description This is a test B
Co-no
Project Proj2
***************************************
Json content
[ {
"Transaction" : "A",
"Description" : "This is a test A",
"Co-no" : "",
"Project" : "Proj1"
}, {
"Transaction" : "B",
"Description" : "This is a test B",
"Co-no" : "",
"Project" : "Proj2"
} ]

PROBLEM:
The file content is type of JSONArray,
[
[
{
"TestScenario_1": {
"Transaction": "A",
"description": "This is a test A",
"Co-no": "",
"Project": "Proj1"
}
}
],
[
{
"TestScenario_2": {
"Transaction": "B",
"description": "This is a test B",
"Co-no": "",
"Project": "Proj2"
}
}
]
]
but at line # 24
JSONObject jo = (JSONObject) jsonParser.parse(reader);
it tried to fetch data(jo) as JSONObject so ClassCastException is occured.
Solutions:
Either change the type of jo Object to JSONArray.
JSONArray jo = (JSONArray) jsonParser.parse(reader);
Or Change the file content by keeping a parent of that array.
{
[
{
"TestScenario_1": {
"Transaction": "A",
"description": "This is a test A",
"Co-no": "",
"Project": "Proj1"
}
}
],
[
{
"TestScenario_2": {
"Transaction": "B",
"description": "This is a test B",
"Co-no": "",
"Project": "Proj2"
}
}
]
}

[
{
"TestScenario_1": {
"Transaction": "A",
"description": "This is a test A",
"Co-no": "",
"Project": "Proj1"
}
},
{
"TestScenario_2": {
"Transaction": "B",
"description": "This is a test B",
"Co-no": "",
"Project": "Proj2"
}
}
]
then
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONArray jo = (JSONArray) jsonParser.parse(reader);
// get a String from the JSON object
JSONObject testScenario=(JSONObject) ((JSONObject)jo.get(0)).get("TestScenario_1");
Long transaction = (Long)testScenario.get("Transaction");
System.out.println("transaction " + transaction);
`
use for loop to iterate JSONArray...I am just giving an example

Related

how to remove json object from json Array using org.json.simple

I have a JSON file which is an JSON ARRAY with some JSON Objects and I want to remove the entire json Object if the value of longitude or latitude is an empty string "".
I am using the library org.json.simple. Here is my json file:
[ { "Longitude": 9.96233,
"Latitude": 49.80404 },
{
"Longitude": 6.11499,
"Latitude": 50.76891
},
{ "Longitude": 6.80592,
"Latitude": 51.53548
},
{
"Longitude": 9.50523,
"Latitude": 51.31991 },
{
"Longitude": ""
"Latitude": ""
},
{
"Longitude": 9.93368,
"Latitude": ""
},
{
"Longitude": 11.56122,
"Latitude": 48.14496
},
{
"Longitude": 13.34253,
"Latitude": 52.5319
},
{
"Longitude": 6.11327,
"Latitude": 50.77715
},
{
"Longitude": ""
"Latitude": ""
}
]
and here's where I am stuck. :
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader ("output.json")) {
Object obj = jsonParser.parse(reader);
JSONArray list = (JSONArray) obj;
list.forEach(node -> {
String vari = (String)((JSONObject)node).get("longitude").toString();
if (vari==null) {
((JSONObject) node).remove();
System.out.println("deleted");
}
}
...
Any suggestions how can I change my code ?
You need to remove the node from the list but because of concurrent modification problem (modifying the list you are looping) you need another list.
I think it is easiest to collect into the new list all the nodes that qualify so like:
#SuppressWarnings("unchecked")
#Test
public void test() throws Exception {
JSONParser jsonParser = new JSONParser();
JSONArray listNonNull = new JSONArray();
try (FileReader reader = new FileReader("output.json")) {
JSONArray list = (JSONArray) jsonParser.parse(reader);
((Collection<JSONObject>)list).forEach(node -> {
// here any check that qualifies the node like also checking "Latitude"
// Also no need to cast to a String
Object vari = node.get("Longitude");
if (vari != null && !vari.equals("")) {
listNonNull.add(node);
}
});
} catch (Exception e) {
throw e;
}
}
If you wish to use only the original list you can collect items to be removed to an another list and use it to remove nodes from the original list:
public void test2() throws Exception {
JSONParser jsonParser = new JSONParser();
JSONArray toBeRemoved = new JSONArray();
try (FileReader reader = new FileReader("output.json")) {
JSONArray list = (JSONArray) jsonParser.parse(reader);
((Collection<JSONObject>) list).forEach(node -> {
Object vari = node.get("Longitude");
// here any check that qualifies the node like also checking "Latitude"
if (vari != null && !vari.equals("")) {
return; // not to be removed
}
toBeRemoved.add(node);
});
list.removeAll(toBeRemoved);
} catch (Exception e) {
throw e;
}
}
use .remove instead of .clear in the code.
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("output.json")) {
Object obj = jsonParser.parse(reader);
JSONArray list = (JSONArray) obj;
ArrayList<JSONObject> objList = (ArrayList<JSONObject>) list.stream().filter(node -> {
String longitude = ((JSONObject) node).get("Longitude").toString();
String latitude = ((JSONObject) node).get("Latitude").toString();
if (longitude.isEmpty() || latitude.isEmpty()) {
return false;
}
return true;
}).collect(Collectors.toList());
} catch (IOException | ParseException e) {
e.printStackTrace();
}

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

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

How can I parse a local JSON file from assets folder into a ListView?

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

How do I convert a JSON array into a Java List. I'm using svenson

I am trying to convert multiple objects of the same type into a List in Java. For example, my json would be:
{
"Example": [
{
"foo": "a1",
"bar": "b1",
"fubar": "c1"
},
{
"foo": "a2",
"bar": "b2",
"fubar": "c2"
},
{
"foo": "a3",
"bar": "b3",
"fubar": "c3"
}
]
}
I have a class:
public class Example {
private String foo;
private String bar;
private String fubar;
public Example(){};
public void setFoo(String f){
foo = f;
}
public void setBar(String b){
bar = b;
}
public void setFubar(String f){
fubar = f;
}
...
}
I want to be able to turn the json string I get into a list of Example objects. I would like to do something like this:
JSONParser parser = new JSONParser();
parser.addTypeHint(".Example[]", Example.class);
List<Example> result = parser.parse(List.class, json);
Doing this I get an error:
Cannot set property Example on class java.util.ArrayList
You cannot convert this json to List but you can convert this to Map.
See your json String:
...
"Example": [
{
"foo": "a1",
"bar": "b1",
"fubar": "c1"
},
{
"foo": "a2",
"bar": "b2",
"fubar": "c2"
},
...
]
}
Here "Example" is key(String) and value is List object of Example.
Try this:
parser.addTypeHint("Example[]", Example.class);
Map<String,List<Example>> result1 = parser.parse(Map.class, json);
for (Entry<String, List<Example>> entry : result1.entrySet()) {
for (Example example : entry.getValue()) {
System.out.println("VALUE :->"+ example.getFoo());
}
}
Full code of Example:
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.svenson.JSONParser;
public class Test {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
parser.addTypeHint(".Example[]", Example.class);
String json = "{" + "\"Example\": [" + "{" + "\"foo\": \"a1\","
+ "\"bar\": \"b1\"," + "\"fubar\": \"c1\"" + "}," + "{"
+ "\"foo\": \"a2\"," + "\"bar\": \"b2\"," + "\"fubar\": \"c2\""
+ "}," + "{" + "\"foo\": \"a3\"," + "\"bar\": \"b3\","
+ "\"fubar\": \"c3\"" + "}" + "]" + "}\"";
parser.addTypeHint("Example[]", Example.class);
Map<String, List<Example>> result1 = parser.parse(Map.class, json);
for (Entry<String, List<Example>> entry : result1.entrySet()) {
for (Example example : entry.getValue()) {
System.out.println("VALUE :->" + example.getFoo());
}
}
}
}
public class Example {
private String foo;
private String bar;
private String fubar;
public Example(){}
public void setFoo(String foo) {
this.foo = foo;
}
public String getFoo() {
return foo;
}
public void setBar(String bar) {
this.bar = bar;
}
public String getBar() {
return bar;
}
public void setFubar(String fubar) {
this.fubar = fubar;
}
public String getFubar() {
return fubar;
}
}
OutPut:
VALUE :->a1
VALUE :->a2
VALUE :->a3
I solved it by modifying my JSON to be in the form:
[
{
"foo": "a1",
"bar": "b1",
"fubar": "c1"
},
{
"foo": "a2",
"bar": "b2",
"fubar": "c2"
},
{
"foo": "a3",
"bar": "b3",
"fubar": "c3"
}
]
Then I used the java code:
JSONParser parser = new JSONParser();
ArrayList list = parser.parse(ArrayList.class, json);
List<Example> result = new ArrayList<Example>();
for(int i = 0 ; i < list.size() ; i++){
HashMap<String, String> map = (HashMap) list.get(i);
Example example = new Example();
example.setFoo(map.get("foo"));
example.setBar(map.get("bar"));
example.setFubar(map.get("fubar"));
result.add(example);
}
i have a jsonstring like this :
[
{"author":"amahta","bookId":1,"bookName":"name"},
{"author":"amahta2","bookId":2,"bookName":"name2"}
]
and convert it to list by this snippet of code:
List<BookVO> listdata = new ArrayList<BookVO>();
JSONArray jArray = JSONArray.fromObject(booklist);
if (jArray != null) {
for (int i = 0; i < jArray.size(); i++) {
JSONObject obj = JSONObject.fromObject(jArray.get(i));
listdata.add(new BookVO(Long.valueOf(obj.get("bookId")), obj.get("bookName"), obj.get("author")));
}
}
i use net.sf.json-lib jar file.
String paymentMethod = "[{\"paymentType\":\"google_iap\",\"msisdn\":1486890084928,\"operator\":\"maroc_ma\",\"paymentMethod\":\"maroc_ma\",\"reactivationEnabled\":true }]";
PaymentMethod mop = null;
try {
mop = mapper.readValue(paymentMethod, PaymentMethod.class);
} catch (Exception e) {
logger.warn("Error while parsing paymentMethod = " + paymentMethod + " \n" + e);
}
List<PaymentMethod> result = new ArrayList<PaymentMethod>();
result.add(mop);
billingInfo.setPaymentMethods(result);

Categories

Resources