I'm parsing this document:
http://pastebin.com/M3Gsbf1t
as you can see it's kind of big. This document was generated by Youtube Data API v3.
I want to get all "title" elements and display them.
My code:
Object obj = parser.parse(str); // str contains the JSON code
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("title");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
but it returns "NullPointerException".
If I replace the "title" with the "items" it works fine but it returns me a lot of informations that I don't need.
I'm using the JSON.simple library.
Thanks for help :)
This code should work:
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("items");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
//System.out.println(iterator.next());
JSONObject item = (JSONObject) iterator.next();
JSONObject item_snippet = (JSONObject) item.get("snippet");
System.out.println( item_snippet.get("title"));
}
You have a JSONObject at the root of your JSON string. In it, there's an JSONArray named items. From it you have to pull out individual items in while loop.
For each item there's JSONObject snippet nested in. Finally you'll find your title string in it.
jquery solution, this should give you an array of titles unless I am reading the object wrong.
titles = [];
obj = $.parseJSON(str);
$.each(obj.items,function(i,v{
titles.push(v.snippet.title);
});
Should be something like this:
Object obj = parser.parse(str); // str contains the JSON code
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("items");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
// cast next item to JSONObject
JSONObject item = (JSONObject) iterator.next();
// grab the title
System.out.println(item.get("title"));
}
Related
My JSON data look like this.
{"Users":[
{"Username":"Admin1", "Password":"123"},
{"Username":"Admin2", "Password":"456"},
{"Username":"Admin3", "Password":"789"}
]}
I am trying to extract out all the list of Username and Password.
JSONParser parser=new JSONParser();
Object obj = parser.parse(new FileReader("./Database/Users.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray userArray = (JSONArray) jsonObject.get("Users");
How do I then iterate through this JSONArray to achieve what I wanted?
Sorry if I wasn't clear. I was using org.json.simple, not org.json. And the JSONArray does not have the int length() method.
What I did was
Iterator<JSONObject> iterator = userArray.iterator();
while (iterator.hasNext()) {
JSONObject factObj = (JSONObject) iterator.next();
String userName = (String) factObj.get("Username");
String passWord = (String) factObj.get("Password");
}
Read the javadoc ;)
If you are using org.json.JSONArray, you can loop using int length() to know the array's length and Object get(index) or JSONObject getJSONObject(index) to get an item of the array.
You can iterate with for loop
for (int i = 0; i < userArray.length(); ++i) {
JSONObject user = recs.getJSONObject(i);
...
}
you can probably do something like the following
for(int i = 0; i < userArray.length; i++) {
JSONObject user = userArray.getJSONObject(i);
String username = user.getString("Username");
String password = user.getString("Password");
//etc
}
I am a newbie to json parsing, I have grabbed a json string from a request and now I need to parse it with java. I'm using simple-lib for this. But I'm really stuck as I'm not familiar with it. I need to extract following data
I used following java code for that but it's not giving me the result I need, please someone help me...
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("content");
Iterator<String> iterator = msg.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
Sample JSON
{
"status": 200,
"message": "ok",
"timestamp": "2014-05-22T14:29:56.824+03:00",
"pagesCount": 1,
"version": "1.1",
"pages": [
{
"number": 100,
"subpages": [
{
"number": 1,
"timestamp": "2014-05-22T13:41:41.116+03:00",
"content": "text"
},
Something like this perhaps?
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) jsonObject.get("pages");
if (pages != null) {
for (Object p : pages) {
JSONObject page = (JSONObject) p;
JSONArray subPages = (JSONArray) page.get("subpages");
if (subPages != null) {
for (Object sp : subPages) {
JSONObject subPage = (JSONObject) sp;
System.err.println(subPage.get("content"));
}
}
}
}
You are requesting for the value that corresponds to the key content from your outermost object, but no such key exists in your sample input. In addition, the only field named content has a string as its value and not a JSON array.
To get at the content field you would need to walk the object hierarchy until you reach the element that you need, using something along these lines:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) json.get("pages");
// Page 10
JSONObject page = (JSONObject) pages.get(10);
// Subpages of page 10
JSONArray subpages = (JSONArray) page.get("subpages");
// Subpage 7 of page 10
JSONObject subpage = (JSONObject) subpages.get(10);
// Content of subpage 7 of page 10
String content = (String) subpage.get("content");
Please note that I am assuming that e.g. index 10 corresponds to page 10. That may not be true in your case; pages may not be zero-indexed, there may be missing pages or they may not be in the correct order. In that case you will have to iterate over the page and subpage lists and test the value of the number field to find the object that you need.
In any case, if you are indeed using json-simple, as seems to be the case, then JSONObject is a subclass of HashMap and JSONArray a subclass of ArrayList. Therefore, their interfaces should be quite familiar to you.
Disclaimer: Untested code - exception and other error handling removed for brevity
First of all, The json is not valid (if you pasted it complete)
In JSON "{}" is an object, and "[]" is an array, others are just key value pairs.
Simply you can do like this without using parser ,
JSONObject objResponseJSON = new JSONObject(responseJSONString);
int status = (int) objResponseJSON.getInt("status");
//fetch other
JSONArray pages = objResponseJSON.getJSONArray("pages");
for(int count = 0; count < pages.length(); count++){
//fetch other
JSONObject objJSON = pages.getJSONObject(count);
JSONArray subpages = objJSON.getJSONArray("subpages");
for(int count1 = 0; count1 < subpages.length(); count1++){
JSONObject objSubpageJSON = subpages.getJSONObject(count1);
//fetch other
int number = (int) objSubpageJSON.getInt("number");
}
}
I am creating a JSON object in which i am adding a key and a value which is an array. The value for both key and value comes from a TreeSet which has data in sorted form. However, when I insert data in my json object, it is stored randomly without any order.
This is my json object currently:
{
"SPAIN":["SPAIN","this"],
"TAIWAN":["TAIWAN","this"],
"NORWAY":["NORWAY","this"],
"LATIN_AMERICA":["LATIN_AMERICA","this"]
}
and my code is:
Iterator<String> it= MyTreeSet.iterator();
while (it.hasNext()) {
String country = it.next();
System.out.println("----country"+country);
JSONArray jsonArray = new JSONArray();
jsonArray.put(country);
jsonArray.put("this);
jsonObj.put(country, jsonArray);
}
Is there any way I can store the data into my json object inside the while loop itself?
Even if this post is quite old, I thought it is worth posting an alternative without GSON:
First store your keys in an ArrayList, then sort it and loop through the ArrayList of keys:
Iterator<String> it= MyTreeSet.iterator();
ArrayList<String>keys = new ArrayList();
while (it.hasNext()) {
keys.add(it.next());
}
Collections.sort(keys);
for (int i = 0; i < keys.size(); i++) {
String country = keys.get(i);
System.out.println("----country"+country);
JSONArray jsonArray = new JSONArray();
jsonArray.put(country);
jsonArray.put("this");
jsonObj.put(country, jsonArray);
}
It works with Google Gson API. Try it out.
try{
TreeSet<String> MyTreeSet = new TreeSet<String>();
MyTreeSet.add("SPAIN");
MyTreeSet.add("TAIWNA");
MyTreeSet.add("INDIA");
MyTreeSet.add("JAPAN");
System.out.println(MyTreeSet);
Iterator<String> it= MyTreeSet.iterator();
JsonObject gsonObj = new JsonObject();
JSONObject jsonObj = new JSONObject();
while (it.hasNext()) {
String country = it.next();
System.out.println("----country"+country);
JSONArray jsonArray = new JSONArray();
jsonArray.put(country);
jsonArray.put("this");
jsonObj.put(country, jsonArray);
JsonArray gsonArray = new JsonArray();
gsonArray.add(new JsonPrimitive("country"));
gsonArray.add(new JsonPrimitive("this"));
gsonObj.add(country, gsonArray);
}
System.out.println(gsonObj.toString());
System.out.println(jsonObj.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Below are what the doc says from http://www.json.org/java/index.html.
"A JSONObject is an unordered collection of name/value pairs."
"A JSONArray is an ordered sequence of values. "
In order to get an sorted Json Object, you can use Gson which is already provided a good answer by #user748316.
I have a JSON Object which converted into String and saved into database .But when i am trying to get it back it is throwing exception.My object is something like that...
{"COLUMN":["Type","Sub Type","F.P.","P.P.","Process","Due To Start"]}
How can we get the data back in Normal form?
My Java Code is.....
JSONObject obj = new JSONObject();
JSONArray the_json_array = obj.getJSONArray(userReorderOption);
int size = the_json_array.size();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
arrays.add(another_json_object);
}
And Exception i am getting....
net.sf.json.JSONException: JSONObject["{\"TASKLIST_COLUMN_REORDER\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}"] is not a JSONArray.
And this is java Code how i am creating JSON Object and saving into database...
String userReorderSelection;
Set set = new LinkedHashSet(userReorderSelection);
JSONObject json = new JSONObject();
json.accumulate("COLUMN", set);
saveJSONObj("PrimaryKeyColumn", json.toString());
Thanks Tichodroma,
But as i told i am using net.sf.json.JSONObject class and above things we can achieve from this class too..What i did to solve the above issue?...Please have a look on the Java code...
JSONObject jsonObj = new JSONObject();
JSONObject obj = jsonObj.fromObject(userReorderOption);
JSONArray columnName = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < columnName.size(); i++) {
System.out.println(columnName.getString(i));
}
This code work fine for me with my Json Jar**(net.sf.json)**
Your JSON is not a JSONArray.
A JSONArray is an ordered sequence of values.
You have a JSONObject.
A JSONObject is an unordered collection of name/value pairs.
Edit:
Using the JSON implementation from org.codehaus.jettison.json, you can do this:
String json = "{\"COLUMN\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}";
JSONObject obj = new JSONObject(json);
JSONArray column = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < column.length(); i++) {
final String field = column.getString(i);
System.out.println(field);
}
Result:
Type
Sub Type
F.P.
P.P.
Process
Due To Start
I am trying to iterate through a file in the file system which contains configuration information for numerous devices.
The file is in this format:
{
"myDevicesInfo":
[
{
"DeviceType":"foo",
"DeviceName":"foo1",
"IPAddress":"192.168.1.1",
"UserName":"admin",
"Password":"pw"
}
]
}
I am getting the following error when trying to get the inner key-value pairs:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at mav2bac.loadDevices(bac.java:98)
at mav2bac.main(bac.java:70)
File appBase = new File("."); //current directory
String path = appBase.getAbsolutePath();
System.out.println(path);
Object obj = parser.parse(new FileReader("bac.yml"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonObjectDevice = (JSONObject)jsonObject;
JSONObject deviceAttributes = (JSONObject) jsonObject.get("myDevicesInfo");
Map json = (Map)parser.parse(jsonObject.toJSONString(), containerFactory);
System.out.println(json.values());
Iterator iter = json.entrySet().iterator();
System.out.println("==iterate result==");
while(iter.hasNext()){
Map.Entry entry = (Map.Entry)iter.next();
//System.out.println(entry.getKey() + "=>" + entry.getValue());
System.out.println(entry.getValue());
}
So what is the proper way to get convert use ContainerFactory and instantiate an object containing these values?
The problem is that myDevicesInfo is an array of json objects and not a json object. so the following line:
JSONObject deviceAttributes = (JSONObject) jsonObject.get("myDevicesInfo");
needs to change to
JSONArray deviceAttributes = (JSONArray) jsonObject.get("myDevicesInfo");
Try this :
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(pathToJsonFile));
JSONArray features = (JSONArray) jsonObject.get("myDevicesInfo");
Iterator itr=features.iterator();
while(itr.hasNext()){
JSONObject featureJsonObj = (JSONObject)itr.next();
String deviceType = (String)featureJsonObj.get("DeviceType");
String deviceName = (String) featureJsonObj.get("DeviceName");
String ipadd = (String) featureJsonObj.get("IPAddress");
String uname = (String) featureJsonObj.get("UserName");
String pwd = (String) featureJsonObj.get("Password");
}