I've a kept one text file in res/raw folder in eclipse. I am showing here the content of that file:
{
"Categories": {
"Category": [
{
"cat_id": "3",
"cat_name": "test"
},
{
"cat_id": "4",
"cat_name": "test1"
},
{
"cat_id": "5",
"cat_name": "test2"
},
{
"cat_id": "6",
"cat_name": "test3"
}
]
}
}
I want to parse this JSON array. How can I do this?
Can anybody please help me??
Thanks in advance.
//Get Data From Text Resource File Contains Json Data.
InputStream inputStream = getResources().openRawResource(R.raw.json);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("Text Data", byteArrayOutputStream.toString());
try {
// Parse the data into jsonobject to get original data in form of json.
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("Categories");
JSONArray jArray = jObjectResult.getJSONArray("Category");
String cat_Id = "";
String cat_name = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
cat_Id = jArray.getJSONObject(i).getString("cat_id");
cat_name = jArray.getJSONObject(i).getString("cat_name");
Log.v("Cat ID", cat_Id);
Log.v("Cat Name", cat_name);
data.add(new String[] { cat_Id, cat_name });
}
} catch (Exception e) {
e.printStackTrace();
}
This is your code:
String fileContent;
JSONObject jobj = new JSONObject(fileContent);
JSONObject categories = jobj.getJSONObject("Categories");
JSONArray listCategory = categories.getJSONArray("Category");
for( int i = 0; i < listCategory.length(); i++ ) {
JSONObject entry = listCategory.getJSONObject(i);
//DO STUFF
}
Android framework has a helper JsonReader in android.util package
Works like a charm, presented great example. In first block small error with absent square bracket '}':
public List readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
try {
return readMessagesArray(reader);
} finally {
reader.close();
}
}
Also exists great library from google-devs GSON, which gives you possibility to map json structure straight to Java model: take a look here
Read it into a String
Create a JSONArray with the retrieved String
Use get() methods to retrieve its data
Related
{
"batchcomplete": "",
"query": {
"pages": {
"25675557": {
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
}
}
}
}
this is the code I tried :
public void getJSON(final String city) throws JSONException {
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + city);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = "";
while ((tmp = reader.readLine()) != null) {
json.append(tmp).append("\n");
}
reader.close();
data = new JSONObject(json.toString());
if (data.getInt("cod") != 200) {
System.out.println("Cancelled");
return null;
}
} catch (Exception e) {
System.out.println("Exception " + e.getMessage());
return null;
}
return null;
}
#Override
protected void onPostExecute(Void Void) {
if (data != null) {
Log.d("my weather received", data.toString());
try {
//JSONObject forecastJson = new JSONObject(data);
JSONObject forecastArray = data.getJSONObject("query");
System.out.println(forecastArray);
JSONArray pagesArray = forecastArray.getJSONArray("pages");
// JSONArray idArray = pagesArray.getJSONArray(0);
//JSONArray idArray = pagesArray.get(0);
System.out.println(pagesArray);
JSONObject obj = pagesArray.getJSONObject(0);
System.out.println(obj);
//JSONObject weatherarray = data.getJSONObject("pages");
//JSONObject weather = weatherarray.getJSONObject(0);
// final String des = weather.getString("description");
/*for (int i = 0; i < forecastArray.length(); i++) {
JSONObject dailyForecast = forecastArray.getJSONObject(i);
JSONObject tempObject = dailyForecast.getJSONObject("main");
minTemp = tempObject.getDouble("min");
maxTemp = tempObject.getDouble("max");
//add these minTemp and maxTemp to array or the
//way you want to use
}*/
System.out.println("Temp Value : "+" : ");
runOnUiThread(new Runnable() {
#Override
public void run() {
textvw.setText("");
}
});
} catch (Exception e) {
Log.e("GetFeedTask", "Error:" + e.getMessage());
}
}
}
}.execute();
}
The exception is because the response does not contain JSON Array. Change your
JSONArray pagesArray = forecastArray.getJSONArray("pages");
to
JSONObject pagesArray = forecastArray.getJSONObject("pages");
and I believe that you're trying to get keys which are dynamic. You cloud get the objects using JSONObject.getKeys() like below.
Iterator keys = pagesArray.keys();
while(keys.hasNext()) {
String dynamicKey = (String)keys.next();
JSONObject jObj = pagesArray.getJSONObject(dynamicKey);
//Get other attributes by jObj.getString() method.
}
Try and let me know if it works.
The error is clear enough. you try to assign a JSONobject to a JSONArray
JSONArray pagesArray = forecastArray.getJSONArray("pages");
Replace by
JSONObject pagesArray = forecastArray.JSONObject("pages");
the data of a JSONArray are between [] and not {}.
your error is in :
JSONArray pagesArray = forecastArray.getJSONArray("pages");
Your problem is that you getJSONArray while pages are a JsonObject in your data .if your "pages" is a array in your data you must send it in [] from server like this:
{
"batchcomplete": "",
"query": {
"pages": [ {
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
},
{
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
}
]
}
}
and in android :
try {
//JSONObject forecastJson = new JSONObject(data);
JSONObject forecastArray = data.getJSONObject("query");
System.out.println(forecastArray);
JSONArray pagesArray = forecastArray.getJSONArray("pages");
System.out.println(pagesArray);
for (int k = 0; k < pagesArray.length(); k++) {
try {
JSONObject object = pagesArray.getJSONObject(k);
String pageid = object.getString("pageid");
String ns = object.getString("ns");
String title = object.getString("title");
String extract = object.getString("extract");
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e("GetFeedTask", "Error:" + e.getMessage());
}
I'm attempting to use a json file to store user data for a dummy Android Studio project, and while trying to test the LoginActivity which reads in the file, I'm getting an error
Error:Execution failed for task ':app:mergeDebugResources'.
/Users/james/projects/cwm/app/src/debug/res/values/users.json:1:1: Error: Content is not allowed in prolog.
{
"users": [
{
"name": "James",
"email": "j#gmail.com",
"address": "addr1",
"password": "password",
"usertype": "USER"
},
{
"name": "Kayla",
"email": "k#gmail.com",
"address": "addr1",
"password": "password",
"usertype": "MANAGER"
}
]
}
And here is the code in the LoginActivity that I believe is causing the error:
private String loadJSONFromAsset() {
String json = null;
try {
InputStream is = this.getAssets().open("users.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;
}
private void parseJ() {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
if(jsonObject != null) {
JSONArray jsonArray = jsonObject.getJSONArray("users");
if(jsonArray != null) {
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
if(jo != null) {
String name = (String) jo.get("name");
String email = (String) jo.get("email");
String address = (String) jo.get("address");
String password = (String) jo.get("password");
String userType = (String) jo.get("usertype");
User u = new User(name, email, address, password);
u.setUserType(userType);
userList.put(email, u);
a.setMessage(u.toString());
a.show();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I've searched stackoverflow and Google for a solution but most answers pertain to XML or JSON unmarshalling, which I don't believe is relevant to what I'm doing but I could be wrong. Thanks in advance!
/Users/james/projects/cwm/app/src/debug/res/values/users.json:1:1: Error: Content is not allowed in prolog.
Please move your users.json from res folder to assets folder and try again.
Because, getAssets() method refers to assets folder.
It's possible that a byte order mark prevents deserialization. Check that your editor doesn't add one.
Hi guys I have a problem parsing my nested json array. This is my sample json response:
{
"SUCCESS": true,
"DATA": [
{
"ShowData": [
{
"ShowTitle": "Episode 1",
"Category": "Comedy"
},
{
"ShowTitle": "Episode 1a",
"Category": "Drama"
},
{
"ShowTitle": "Mr. Right",
"Category": "Musical"
},
{
"ShowTitle": "The Making",
"Category": "Talk"
},
{
"ShowTitle": "Presscon",
"Category": "Comedy"
},
{
"ShowTitle": "Presscon 2",
"Category": "Drama"
},
{
"ShowTitle": "Episode 2",
"Category": "Comedy"
},
{
"ShowTitle": "Episode 2",
"Category": "Drama"
}
]
}
]
}
This is what I've tried so far:
Activity:
ArrayList<HashMap<String, String>> showsList
= Parser.getShowsResponseBody(response);
ArrayList<HashMap<String, String>> result = new ArrayList<>();
Set<String> titles = new HashSet<>();
for(HashMap<String, String> map : showsList) {
if(titles.add(map.get("Category"))) {
result.add(map);
}
}
Parser:
public static List<Show> getShowsResponseBody(Response response) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
List<WorldShow> list = new ArrayList<>();
try {
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("Data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
JSONArray arr = json_data.getJSONArray("ShowData");
for(int j = 0; j < arr.length(); j++) {
JSONObject innerData = arr.getJSONObject(j);
Show show = new Show(); // Create Object here
show.setShowTitle(innerData.getString("ShowTitle"));
show.setCategory(innerData.getString("Category"));
list.add(show); // Finally adding the model to List
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
My expected output is:
Comedy: Episode 1, Presscon, Episode 2
Drama: Episode 1a, Presscon 2, Episode 2
Musical: Mr. Right
Talk: The Making
But when I run the app, it's displaying all the records in all category. What seem to be wrong with my code? I already used HashSet to remove duplicate objects but it's still the same. Any help would be gladly appreciated! Thanks in advance!
// Make a map to hold the mapping between categories and shows:
// (A single category is mapped to a collection of 1 or more shows)
Map<String,List<Show>> catShows = new HashMap<String,List<Show>>();
// Put a Show object into the category map for its matching category:
private void addShow( Map<String,List<Show>> map, Show show ) {
// Get the shows already stored under that category:
List<Show> list = map.get( show.getCategory() );
if ( list == null ) {
// There's no entry for that category yet, so we create a new (empty) list:
list = new ArrayList<Show>();
// Store the new list for its category:
map.put( show.getCategory(), list );
}
// Add the given show to the list for its category:
list.add( show );
}
// Example for how to iterate over the map created above:
private void process( Map<String,List<Show>> map ) {
for ( Map.Entry<String, List<Show>> e : map.entrySet() ) {
final String category = e.getKey();
final List<Show> shows = e.getValue();
// Now we have in shows the list of all shows for the category.
System.out.println( "Cat: " + category );
// Output all shows for the current category:
for ( Show s : shows ) {
System.out.println ( s.getShowTitle() );
}
}
}
I think you might change your approach.
I suggest you to use GSon Library and create a class that represents your json:
Possible scenario:
Result.class
public class Result{
boolean success;
List<Data> data;
//getter and setter
}
Data.class
public class Data{
List<Item> items;
//getter and setter
}
Item.class
public class Item{
String ShowTitle;
String Category;
//getter and setter
}
to parse json:
Gson gson = new Gson();
Result result = gson.fromJson(json, Result.class);
check this
I have local Json file in asset folder.
I use this code to open file
try {
is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonString = is.toString();
jsonString = new String(buffer,"UTF-8");
myJson = new JSONObject(jsonString);
jsonArrayData = myJson.getJSONArray("diTich");
int leng = jsonArrayData.length();
for(int i = 0 ; i < leng ; i++) {
mTitle = jsonArrayData.getJSONObject(i).getString("title");
mDescription = jsonArrayData.getJSONObject(i).getString("description");
mAddress = jsonArrayData.getJSONObject(i).getString("address");
mStatus = jsonArrayData.getJSONObject(i).getString("status");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
My's Json file
{
"ABCD": [
{
"title": "abcd",
"description": "abc",
"address": "bnc",
"image": "abcg",
"status": false
}
]
}
I retrieved value in JsonObject. Now I wanna edit value in this
For example, change value of key "status" from false to true.
How can I do this ? I don't know write replace it !
Thanks you guys !
You use the JSONObject.put() methods of the JSONObject class. So, in your example you could do this:
jsonArrayData.getJSONObject(i).put("status", true);
That will clobber the value that is currently there.
How can i extract the json below and save it in an arraylist.
{
"trains": {
"train": [
{
"#id": 1000000103,
"#version": 1,
"#status": "active",
"#name": "dffffff",
"#description": "ffffff half of the nineteenth century.",
"#city": "fff",
"#phone": "+230 595-1454",
"#email": "ffffr#mffc.mu",
"#website": "www4u",
"#latitude": -5.2882,
"#longitude": 3.499,
"#defaultLocale": "",
"#holes": 48,
"#par": 72,
"#slope": 0,
"#distance": 5.005273,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
},
{
"#id": 1000000105,
"#version": 1,
"#status": "active",
"#name": " xClub",
"#description": "",
"#city": " xlet",
"#phone": "+44465\t",
"#email": "",
"#website": "wweffl.com",
"#latitude": -2.040318,
"#longitude": 54548,
"#defaultLocale": "",
"#holes": 18,
"#par": 32,
"#slope": 0,
"#distance": 2441673,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
}
]
}
}
my working
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
String jsonobj = jobj_trouve_golf.getString("trains");
//String jsonobj1 = jobj_trouve_golf.getString("train");
//jobj_trouve_train = new JSONObject(reponse_trouve_train);
//jsonArray = jobj_trouve_golf.getJSONArray("trains");
//jsonArray= new JSONArray(jsonobj);
//System.out.println("jsonArray "+jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this..
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
JSONObject jsonobj = jobj_trouve_train.getJSONObject("trains");
JSONArray jsonobj1 = jsonobj.getJSONArray("train");
for(int i = 0;i< jsonobj1.length();i++){
JSONObject jsonj = jsonobj1.getJSONObject(i);
System.out.println("#id "+jsonj.getString("#id"));
// Same for remaining all
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use the Gson library developed by Google to parse Json into objects.
The reference is here:
https://code.google.com/p/google-gson/
And, a sample example is here:
JSON Parsing with GSON
JSONObject trains = jobj_trouve_train.getJSONObject("trains");
JSONArray trainArray = trains.getJSONArray("train");
JSONObject train1 = trainArray.getJSONObject(0);
...
if i didn't get confuse maybe this one will be right
JSONArray jasonArray = new JSONArray(result.getProperty("trains").toString());
for (int i = 0; i < jasonArray.length(); i++) {
JSONObject jsonObj = jasonArray.optJSONObject(i);
trainObject = new JSONObject(jsonObj.optString("train").toString());
int id = trainObject.optInt("id");
and so on..
}
public Object void toObject(String jsonMsg) throws JSONException {
JSONObject trains= (JSONObject) new JSONTokener(jsonMsg).nextValue();
if(trains.has("trains")){
JSONArray train = (JSONArray) new JSONTokener(object.getString("train")).nextValue();
for (int t = 0; t < jsonArray.length(); t++) {
String temp = jsonArray.getJSONObject(t).toString();
JSONObject object = (JSONObject) new JSONTokener(temp).nextValue();
if(object.has("#id"))
object.getString("#id");
// now similar procedure of reading
// read values and save it in an "object"
}
return savedObject;
}
-- tested, i have tried to modify code to match your JSON data. complete the rest.