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;
}
}
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();
}
I am trying to parse json file using Java.My json file format is given below.I was trying to print a message if the action is a "note" and print performed_at. However,there is no output for the below code.
Thanks in advance for the advice and your time.Appreciate it.
{
"data": {
"name": "John"
},
"activities_data": [{
"performed_at": "April",
"id": 630,
"action": {
"address": "N/A",
"issue_type": "F A"
}
},
{
"performed_at": "March",
"id": 687,
"action": {
"note": {
"id": 26519,
"type": 4
}
}
}
]
}
Java code:
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;
import java.io.Reader;
import java.util.Iterator;
import java.util.Map;
public class Readjsonfile {
public static void main(String[] args) throws Exception {
JSONParser parser = new JSONParser();
JSONObject ticketObject = (JSONObject) parser.parse(new FileReader("activity.json"));
JSONArray jsonArray= (JSONArray) ticketObject.get("activities_data");
for(int i=0; i<jsonArray.size(); i++){
Map activityobject = ((Map)jsonArray.get(i));
System.out.println(activityobject);
if (activityobject.containsKey("note"))
{
System.out.println("its a note");
\\and print performed_at here
}
}
}
}
You should nest a level deeper to get the note.
for(int i=0; i<jsonArray.size(); i++){
Map activityobject = ((Map)jsonArray.get(i));
System.out.println(activityobject);
if (activityobject.containsKey("action")) {
Map actionObject = ((Map)activityobject.get("action"));
if (actionObject.containsKey("note")) {
System.out.println("its a note");
System.out.println("note" + actionObject.get("note"));
System.out.println("Performed at " + activityobject.get("performed_at"));
}
}
}
Output
{"performed_at":"April","action":{"address":"N\/A","issue_type":"F A"},"id":630}
{"performed_at":"March","action":{"note":{"id":26519,"type":4}},"id":687}
its a note
note{"id":26519,"type":4}
Performed at March
You should get a JsonObject, not a Map:
JSONObject activityobject = ((JSONObject) jsonArray.get(i));
And then you have to load the action part of the JSON (you can't look for an attribute recursively:
JSONObject actionObject = ((JSONObject) activityobject.get('action'));
And finally you should use has() to check for the attribute you want:
if (actionObject.has('note')) {
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
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 .
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);