I am trying to read the values from a JSON file to array for further processing. I am using JSON-Smart 1.2.0 library for the same. Due to some restrictions, I can not use the 2.0 version.
I am getting the following exception.
java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to net.minidev.json.JSONObject
I am even tried using JSONArray instead of JSONObject. What I am doing wrong over here? Is this correct way to read json content?
Below is the java code.
JSONObject json = (JSONObject) JSONValue.parseWithException(browsers);
JSONArray array = (JSONArray) json.get("friends");
for (int i = 0; i < array.size(); i++) {
JSONObject cap = (JSONObject) array.get(i);
String first = (String) cap.get("name");
System.out.println(first);
}
Below is the json file content.
[
{
"friends": [
{
"id": 0,
"name": "test1"
},
{
"id": 1,
"name": "test2"
}
]
}
]
Your JSON contains an array which has one single object element so you should parse it like that:
JSONArray root = (JSONArray) JSONValue.parseWithException(json);
JSONObject rootObj = (JSONObject) root.get(0);
JSONArray array = (JSONArray) rootObj.get("friends");
for (int i = 0; i < array.size(); i++) {
JSONObject cap = (JSONObject) array.get(i);
String first = (String) cap.get("name");
System.out.println(first);
}
If it can have more elements add a for loop instead of root.get(0).
Related
I have an service that returns me an json object like the below
{
"header": {},
"title": {},
"terms": {
"data": {
"list": [
"string": 1,
"string1": 2,
"string2": 3
]
}
}
}
Now I need to get the keys of the list json array into a list. I have got the array into an object
List<String> allTerms = new ArrayList<String>();
String response = HttpRequest.get("http://myservice/get").body();
JSONParser parser = new JSONParser();
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
JSONObject fieldObj = (JSONObject)jsonObject.get("terms");
JSONObject queryObj = (JSONObject)fieldObj.get("data");
JSONArray termsArr = (JSONArray) queryObj.get("list");
//iterate the termsarr and get the string,string1,string2 keys alone to allTerms list
Is there a more better way to do this? Im using json-simple and a custom http client
By using basic for loop
for(int i=0; i<termsArr.length(); i++) {
String[] arr = termsArr.getString(i).split("\"");
allTerms.add(arr[1]);
}
I have searched everywhere and cannot find out how to do this, I'm super stuck. I have NO experience with JSON files, so spoon feeding is appreciated along with an explanation.
I have this JSON text here for testing:
{
"id":"4566e69fc90748ee8d71d7ba5aa00d20",
"properties":
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
],
"name":"Thinkofdeath",
}
I currently have this:
JsonElement playerProfile = new JsonParser().parse(jsonLine);
JsonObject jsonProfile = playerProfile.getAsJsonObject();
JsonArray properties = jsonProfile.getAsJsonArray("properties");
Which returns
[
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
]
Of course. How do I get the "value" from this JsonArray? Note I'm using Google's API, Gson
You can get values using:
JsonObject propertiesJson = properties.get(0);
String value = propertiesJson.getString("value");
array is JsonArray object from com.google.gson library
for (int i=0; i<array.size(); i++) {
JsonObject json = array.get(i).getAsJsonObject();
String value = json.get("key").getAsString();
}
This is my JSON
{
"data": [
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
}
]
}
]
}
Now I am trying to display it into a listView how would I do that this is what i have right now (for testing purposes i am just trying to display all the names in a toast)
JSONObject jsonObj = new JSONObject(jsonStr);
int length = jsonObj .length();
for(int i=0; i<length; i++) {
Toast.makeText(this, jsonObj.getJSONArray("data").
getJSONObject(i).getString("Name"), Toast.LENGTH_LONG).show();
}
The Above code only display one name and not multiple names. How can I make it for multiple names?
Take a look this code snippet
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name").toString(), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
// getting json objects from Ingredients json array
for(int j=0; j<len; j++)
{
JSONObject json = ja.getJSONObject(j);
Toast.makeText(this, json.getString("name").toString(), Toast.LENGTH_LONG).show();
}
}
I recommend to use 'Log' instead using 'Toast'.
If any confusion or query let me know, i will try my best to resolve it.
If answer is satisfiable please mark it as correct answer.
Happy coding!
Thanks
You are getting the length of JSONObject, but you should get the length of JSONArray inside that JSONObject in order to iterate though json array items.
int length = jsonObj.getJSONArray("data").size()
I think you are guessing it wrong. Look closely you have a Json in that you have array which is JsonArray with the name/key "data"
then in that you can get it and traverse it index by index. For you I am providing you a road map so that things make easy for you conceptually
Make a model class which may able to store the values as you are getting in response of your api or in this json respone.
Take an array of type of your model class to store values
Now you can add for loop to save values or you can parse and save your jason array into your array you made to handle the jasonarray
this is easily be understand by this link and this is a working example to parse the json array and to show in your list view. You have nothing to worry about after reading these two links.
get your result from URL where your json is and store to any variable (result here) , then decode it i am showing below,
try this , it may give you some hint , i have not tried but may help you
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.optJSONArray("data");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
int id = jsonObjects.optInt("id");
String varMessage = jsonObjects.optString("varMessage");
String Image = jsonObjects.optString("Image");
String Category = jsonObjects.optString("Category");
String Method = jsonObjects.optString("Method");
JSONArray jsonArrayIngredients = jsonObject.optJSONArray("Ingredients");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
String name = jsonObjects.optString("name");
}
}
}
I've got an Android app in which I get some JSON from an API, which I now need to decode. I'm pretty far, but I'm failing at getting the contents. The JSON I'm receiving looks like this:
{ "messages": [
{
"created": "1391783287",
"id": 1,
"is_supporter": false,
"text": "Behold! This is a message?"
},
{
"created": "1391783287",
"id": 3,
"is_supporter": true,
"text": "Behave! This is an answer!"
}
]}
And I've got this code:
#Override
protected void onPostExecute(String result) {
try{
JSONArray jArray = new JSONArray(result);
And on the last line of the code above I get an error saying Error: org.json.JSONException: Value {"messages":[{"id":1,"created":"1391788514","text":"How do I pay to an IBAN?","is_supporter":false},{"id":3,"created":"1391788514","text":"What is a payment pool?","is_supporter":false}]} of type org.json.JSONObject cannot be converted to JSONArray
Does anybody have any idea whats wrong here or how I can solve this?
Your String is a JSON object containing a JSON array, try this :
JSONObject myJSON = new JSONObject(result);
JSONArray jArray = myJSON.getJSONArray("messages");
then iterate through your JSONArray ...
int size = jArray.length();
for (int i=0 ; i<size ; i++){
JSONObject itemInArray = jArray.get(i);
// get values inside the object, for example :
String text = itemInArray.getString("text");
}
You can use old http://www.json.org lib in your Java :
First read your json file content into String;
Then parse it into JSONObject, If there is array, then get the array;
JSONObject myJson = new JSONObject(myJsonString);
// get the JsonArray
JSONArray jArray = jobj.getJSONArray("messages");
//Loop through the array to get the JSONObjects
for(int i=0;i<jArray.length();i++) {
// use myJson as needed, for example
int id = jArray.getJsonobject(i).getString("id");
// etc
}
you are JSONArray is in inside the JSONObject
Do like this to get the data
#Override
protected void onPostExecute(String result) {
try {
JSONObject jobj = new JSONObject(result);
JSONArray jArray = jobj.getJSONArray("messages");
for(int i=0;i<jArray.length();i++) {
String created=jArray.getJsonobject(i).getString("created");
}
}
I have data like this:
NewsItem :
id
title
date
txt
There may be many NewsItems say 10. I have to send them to jquery.
I am doing this:
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
for(int i = 0 ; i< list.size() ; i++){
p = list.get(i);
arr.put(p.getId());
arr.put(p.getTitle());
arr.put(new MyDateFormatter().getStringFromDateDifference(p.getCreationDate()));
arr.put(getTrimmedText(p.getText()));
obj.put(""+i,arr);
arr = new JSONArray();
}
This will create a JSON string like this : {"1":["id","title","date","txt"],"2":[......and so on...
Is that correct way of doing this?
How can I parse this string so that I can get each news item object in jQuery so that I can access attr.
Like this:
obj.id,
obj.title
Or if this is wrong way of creating JSON string, please suggest some better way with example of parsing in jQuery.
I believe that you're organizing your data backwards. It seems that you want to use an array of NewsItems, and if so, then your java JSON generation code should look like this:
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
for(int i = 0 ; i< list.size() ; i++)
{
p = list.get(i);
obj.put("id", p.getId());
obj.put("title", p.getTitle());
obj.put("date". new MyDateFormatter().getStringFromDateDifference(p.getCreationDate()));
obj.put("txt", getTrimmedText(p.getText()));
arr.put(obj);
obj = new JSONObject();
}
Now your JSON string will look something like this:
[{"id": "someId", "title": "someTitle", "date": "dateString", "txt": "someTxt"},
{"id": "someOtherId", "title": "someOtherTitle", "date": "anotherDateString", "txt": "someOtherTxt"},
...]
Assuming that your NewsItem gettors return Strings. The JSONObject method put is overloaded to take primitive types also, so if, e.g. your getId returns an int, then it will be added as a bare JSON int. I'll assume that JSONObject.put(String, Object) calls toString on the value, but I can't verify this.
Now in javascript, you can use such a string directly:
var arr =
[{"id": "someId", "title": "someTitle", "date": "dateString", "txt": "someTxt"},
{"id": "someOtherId", "title": "someOtherTitle", "date": "anotherDateString", "txt": "someOtherTxt"}];
for (i = 0; i < arr.length; i++)
alert(arr[i].title); // should show you an alert box with each first title
The idea of the json object is the same as a dictionary/map where you have keys and values assigned to those keys, so what you want to construct would be something like this:
{"1": {"title": "my title", "date": "17-12-2011", "text": "HELLO!"}, "2": ....}
where the "1" is the id and the contents is another dictionary/map with the info.
lets say you assigned the object to a variable named my_map, now you will be able to handle it as:
my_map.1.title
my_map.3.text
...
to iterate over it just use:
for (info in my_map){
data = my_map[info];
//do what you need
}
For converting JSON object to JSON string use
JSON.stringify(json_object)
For reverse use:
JSON.parse(json_string)
This is the correct way -
final JSONArray arr = new JSONArray();
for(int i = 0 ; i< list.size() ; i++) {
final JSONObject obj = new JSONObject();
p = list.get(i);
obj.add("id", p.getId());
obj.add("title", p.getTitle());
obj.add("date", new MyDateFormatter().getStringFromDateDifference(p.getCreationDate()));
obj.add("txt", getTrimmedText(p.getText()));
arr.add(obj);
}
This will generate
[{"id": 1, "date": 222, "title": "abc", "txt": "some text"}, {...}]
Now, when you parse the json at client end, you can iterate over the array and for each json object you can access as -
obj.id or obj["id"]