[Java 17 using the org.json parsing library. Not able to switch to Gson because I've written an insane amount of code in org.json :/ ]
Hello!
I am using an API in Java with the org.json JSON parsing library. I need to get the value of an unnamed JSON object in an array.
{
"lorem": [
{ // this object needs to be retrieved
"ipsum":"dolor",
"sit":"amet",
"consectetur":"adipiscing"
},
{ // this object also needs to be retrieved
"ipsum":"dolor",
"sit":"amet",
"consectetur":"adipiscing"
},
{ // this object needs to be retrieved
"ipsum":"dolor",
"sit":"amet",
"consectetur":"adipiscing"
}
]
}
Note that the entire JSON file is NOT an array, there is just one JSON array inside of a JSON object. How would I be able to get the value of all of these unnamed fields inside of the array?
Thanks in advance for any help, and also sorry if this question has been asked before, I wasn't able to find anything on it when I searched for it on Stackoverflow.
Those objects aren't really unnamed objects, they are part of an JSON array. Because they are contained in an array, we can iterate through that array and we can retrieve every object by index.
Assuming that the we read the json provided above from a file:
public static void main(String[] args) throws FileNotFoundException {
String resourceName = "src/main/resources/input.json";
InputStream inputStream = new FileInputStream(resourceName);
JSONTokener jsonTokener = new JSONTokener(inputStream);
JSONObject jsonObject = new JSONObject(jsonTokener);
// Get the array named lorem from the main object
JSONArray jsonArray = jsonObject.getJSONArray("lorem");
// Iterate through the array and get every element by index
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.println("ipsum:" + object.get("ipsum"));
System.out.println("sit:" + object.get("sit"));
System.out.println("consectetur:" + object.get("consectetur"));
}
}
Also, JSONObject has a toList method, which returns a List<Object>.
Lately i have been trying to consume a Rest service which returns the below rough sample JSON. It has objects which contains Arrays and arrays contains Strings.
{
Main Object:{
Object1:{
}
Object2:{
}
Object3:{
Array1[String1,String2,String3]
Array2[String1,String2,String3]
Array3[String1,String2,String3]
Array4[String1,String2,String3]
}
}}
My requirement is to get all the arrays and check which of the specific array contains specific/required String values and than get those strings to show in jsp.
I am using Spring MVC(Rest Template) but any java based solution would do the work.
P.S: I am New to WebServices.
use JSONArray to get it from below
JSONArray jsonArray = new JSONArray();
jsonArray = JSONObject.getJSONObject("Main Object").getJSONObject("Object3").getJSONArray("Array1");
//Iterate through the above array to get required String.
for the next array :
jsonArray = JSONObject.getJSONObject("Main Object").getJSONObject("Object3").getJSONArray("Array2");
//Iterate through the second array to get required String.
I declared an array as below
String[] finalcodes = new String[50] ;
and assigning some values to it finally when I print finalcodes it results as below.
["aaa","bbb","ccc"]
but my requirement is to get it as a json object
so please suggest me how to convert my string array to JSON Object.
You can use jackson library also check your json is valid;
http://jackson.codehaus.org/ / http://jsonformatter.curiousconcept.com/
When i call server its response is based of json object. Actually, I know how to parse JSON object but this response is strange for me. Server response is:
{"body":"Not Available!","clazz":"SoccerMatchPreview","id":{"inc":-2024241794,"machine":415106952,"new":false,"time":1337861978000,"timeSecond":1337861978},"publishedDate":"2012-06-08 17:00:00 +0100","refKey":"SoccerMatchPreview_4fb897be18be8b87f9117595","title":"Poland vs Greece"}
Those Information that I need are body, publishedDate, refKey and title. The code that i have written based of JSON object is this:
JSONObject jObject = new JSONObject(response);
JSONArray contestantObjects = jObject.getJSONArray("id");
for(int i=0; i<contestantObjects.length(); i++) {
mPreview.setBody(contestantObjects.getJSONObject(i).getString("body").toString());
mPreview.setPublishedDate(contestantObjects.getJSONObject(i).getString("publishedDate").toString());
mPreview.setRefKey(contestantObjects.getJSONObject(i).getString("refKey").toString());
mPreview.setTitle(contestantObjects.getJSONObject(i).getString("title").toString());
}
But because it doesn't have "[]" I think it's not JSON object. therefore, I wrote another code based JSON array.
JSONArray contestantObjects = new JSONArray(response);
for(int i=0; i<contestantObjects.length(); i++) {
mPreview.setBody(contestantObjects.getJSONObject(i).getString("body").toString());
mPreview.setPublishedDate(contestantObjects.getJSONObject(i).getString("publishedDate").toString());
mPreview.setRefKey(contestantObjects.getJSONObject(i).getString("refKey").toString());
mPreview.setTitle(contestantObjects.getJSONObject(i).getString("title").toString());
}
but result is same and Logcat shows:
Value {"id":{"timeSecond":1337861978,"time":1337861978000,"new":false,"machine":415106952,"inc":-2024241794},"body":"Not Available!","title":"Poland vs Greece","publishedDate":"2012-06-08 17:00:00 +0100","clazz":"SoccerMatchPreview","refKey":"SoccerMatchPreview_4fb897be18be8b87f9117595"} of type org.json.JSONObject cannot be converted to JSONArray
any suggestion would be appreciated. Thanks
JSONArray contestantObjects = jObject.getJSONArray("id");
Your error is here, id is itself a complex object, not an array.
"id":{"inc":-2024241794,"machine":415106952,"new":false,"time":1337861978000,"timeSecond":1337861978}
Therefore, after getting the id JSON object, you should be able to get the individual attributes, e.g. inc, machine, new, time, and timeSecond.
JSONObject idObject = ...getJSONObject("id");
String machine = idObject.get("machine");
A JSON array data structure would have looked like this: [] signifies an array.
For example, "Animals":["Pig", "Cat", "Dog"].
In another example, it can also be an Array of complex objects, "Animals":[{"name":"AAA", "blood":"A"}, {"name":"BBB", "blood":"B"}].
EDIT: Here is a good JSON visualizer i would recommend.
http://jsonviewer.stack.hu/
I need help with parsing json string in Java Android Appl.
Text of JSON file:
{"data":{"columns":["location_id","name","description","latitude","longitude","error","type","type_id","icon_media_id","item_qty","hidden","force_view"],"rows":[[2,"Editor","",43.076014654537,-89.399642451567,25,"Npc",1,0,1,"0","0"],[3,"Dow Recruiter","",43.07550842555,-89.399381822662,25,"Npc",2,0,1,"0","0"] [4,"Protestor","",43.074933,-89.400438,25,"Npc",3,0,1,"0","0"],[5,"State Legislator","",43.074868061524,-89.402136196317,25,"Npc",4,0,1,"0","0"],[6,"Marchers Bascom","",43.075296413877,-89.403374183615,25,"Node",22,0,1,"0","0"] [7,"Mary","",43.074997865584,-89.404967573966,25,"Npc",7,0,1,"0","0"]]},"returnCode":0,"returnCodeDescription":null}
How can get values: location_id, name, latitude, longitude.
Thanks, Michal.
Using manual parsing you can implement it like this:
JSONArray pages = new JSONArray(jsonString);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
JSONObject jsonPage =rec.getJSONObject("page");
String address = jsonPage.getString("url");
String name = jsonPage.getString("name");
String status = jsonPage.getString("status");
}
in your case note that your outer elemnt data is type of JSONObject and then you have a JSONArray
mine json file:
[{"page":{"created_at":"2011-07-04T12:01:00Z","id":1,"name":"Unknown Page","ping_at":"2011-07-04T12:06:00Z","status":"up","updated_at":"2011-07-04T12:01:00Z","url":"http://www.iana.org/domains/example/","user_id":2}},{"page":{"created_at":"2011-07-04T12:01:03Z","id":3,"name":"Down Page","ping_at":"2011-07-04T12:06:03Z","status":"up","updated_at":"2011-07-04T12:01:03Z","url":"http://www.iana.org/domains/example/","user_id":2}}]
note that mine starts from [, which means an array, but yours from { and then you have [ array inside. If you run it with a debugger, you can see exactly what´s inside your json objects.
There are also better approaches like:
Jackson
Jackson-JR (light-weight Jackson)
GSON
All of them can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
First of all, you need to know about Json parsing in android, so for that first read this: JSONObject, in that class, you will see the below methods:
getJSONArray(String name)
getJSONObject(String name)
getString(String name)
and many more methods to be used while implementing JSON parsing in android.
Update:
And if you are still confused then click on below link to have many examples available on web: Android JSON Parsing
You need to use the GSON lib
http://code.google.com/p/google-gson/
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
If you mean to navigate easily the Json Tree, you can use JSON Path, that is query system, similar to XPath to XML, that you can use to pick some elements in a json tree using text expressions.
http://code.google.com/p/json-path/ That's a good implementation
If you just mean that you want to parse that JSon you can use Gson from google (that is compatible with Android I guess).
This contains a complete example for your case.