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");
}
Related
I have a problem with JSON, which gives me a casting error on a string. I had already used this code in the past and no error, and I reuse it and boom x)
Here is the line with error:
JSONArray groups = (JSONArray) data.get("groups");
I show you the whole code (the first 3 variables come from a database):
String name = set.getString("name");
UUID uuid = UUID.fromString(set.getString("uuid"));
String json = set.getString("data");
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
JSONObject data = (JSONObject) obj;
String prefix = (String) data.get("prefix");
String suffix = (String) data.get("suffix");
boolean superUser = (boolean) data.get("super");
JSONArray privileges = (JSONArray) data.get("privileges");
JSONArray groups = (JSONArray) data.get("groups");
PS: I have already searched the internet for the same problem but it is frequently with JSONObject and not JSONArray.
So the json look like this
{
"cover":"AddressBook",
"Addresses":[
{
"id":"1",
"NickName":"Rahul",
"ContactName":"Dravid",
"Company":"Cricket",
"City":"Indore",
"Country":"India",
"Type":"Address"
},
{
"id":"2",
"NickName":"Sachin",
"ContactName":"Tendulkar",
"Company":"Cricket",
"City":"Mumbai",
"Country":"India",
"Type":"Address"
}
]
}
I want to extract the data from the id = 1 using the JSON array, but I am not sure how to use the syntax or some other way the code I have is this :
JSONParser jsonParser = new JSONParser();
FileReader reader = new FileReader("AddressBook.json");
Object obj = jsonParser.parse(reader);
address = (JSONArray)obj;
You have to loop through the "Addresses" array.
JSONObject addressBook = (JSONObject) jsonParser.parse(reader);
JSONArray addresses = (JSONArray) addressBook.get("Addresses");
JSONObject address = null;
for (Object find : addresses) {
if (((JSONObject) find).get("id").equals("1")) {
address = (JSONObject) find;
}
}
System.out.println(address.toJSONString());
Output
{"Company":"Cricket","Type":"Address","Country":"India","id":"1","City":"Indore","NickName":"Rahul","ContactName":"Dravid"}
JSON file:
[
{
"name":"John",
"city":"Berlin",
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"job":"Doctor"
}
]
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader("F:\file.json"));
for (Object o : a) {
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
if (name.equalsIgnoreCase("john")) {
String name1 = (String) person.get("name");
System.out.println("name1" + name1);
String city1 = (String) person.get("city");
System.out.println("city1" + city1);
String job1 = (String) person.get("job");
System.out.println("job1" + job1);
person.put("city", "BLR");
String city2 = (String) person.get("city");
System.out.println("city2" + city2);
}
}
Value are not updating in Json external file
JSONObject is a represent of json that does not link to originally file.
To rewrite file you need to change values in person and write it to file.
person.put("city", "BLR");
String jsonString = person.toString();
// write jsonString to file
I'm trying to read data from a JSON file with the following code:
FileReader reader = new FileReader(file);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray dataName = (JSONArray)jsonObject.get("results");
Iterator it = dataName.iterator();
while (it.hasNext()) {
JSONObject out = (JSONObject) it.next();
System.out.printf("Game name: " + out.get("name") + " in plataforms:");
JSONArray data_plat = (JSONArray) out.get("platforms");
if (!data_plat.isEmpty()) {
Iterator it2 = data_plat.iterator();
while (it2.hasNext()) {
System.out.printf("I AM HERE");
JSONObject out_plat = (JSONObject) it2.next();
System.out.printf("\n- " + out_plat.get("name"));
}
}
}
And this code is throwing a NullPointerException in this piece:
if (!dataPlat.isEmpty());
I've analyzed my output and the JSON file and this happens because the part i'm reading contains a null value. How can I avoid this?
EDIT: Here's a part of my JSON:
{
"name":"FIFA Manager 08",
"platforms":[
{
"api_detail_url":"http:\/\/www.giantbomb.com\/api\/platform\/3045-94\/",
"id":94,
"name":"PC",
"site_detail_url":"http:\/\/www.giantbomb.com\/pc\/3045-94\/",
"abbreviation":"PC"
}
],
"resource_type":"game"
},
{
"name":"FIFA Online 2",
"platforms":null,
"resource_type":"game"
},
The error is occurring at the bottom in "platforms":null
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"));
}