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
Related
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"}
As title said I'm new to JSON and I can't get out of my problem. I'm working on this error for 1 week I'm really desperate to get out.
My error :
JSONException: Value [{"data":"11-13-2017","numeVanzator":"Clau","numarClient":0}] at jsonData of type java.lang.String cannot be converted to JSONArray
My JSON:
{
"jsonData" : {
"11-13-2017" : {
"Clau" : {
"-KyokKjL9UQpsfKZYZqM" : [ {
"pret" : "80",
"produs" : "Shirt",
"produsId" : "-Kyok58s0dOAnVOnbJPk"
} ]
}
}
}
}
I looked over tutorials on StackOverFlow but absolutely no solution.
My code :
private void writeJSON(String metodaPlata) throws JSONException {
String numeVanzator = SharedPreference.getString(this, SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR, "");
String jsonDataFromShared = SharedPreference.getString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");
int totalPrice = 0;
for(VanzatorProduse v : Util.getInstance().getVanzatorProduse())
{
int vPrice = Integer.parseInt(v.getPret());
totalPrice = totalPrice + vPrice;
}
String pretTotal = Integer.toString(totalPrice);
String produseSelectate = Integer.toString(listaProdusePreview.getAdapter().getCount());
JSONObject jsonData;
JSONArray dateJSON;
JSONObject obj;
JSONArray arrayForList;
if (jsonDataFromShared.equals("")) {
jsonData = new JSONObject();
dateJSON = new JSONArray();
obj = new JSONObject();
arrayForList = new JSONArray();
JSONObject objListaSiModalitate = new JSONObject();
// arrayForList.put(stock_list.toString());
objListaSiModalitate.put("lista", new JSONArray(Util.getInstance().getVanzatorProduse()));
objListaSiModalitate.put("metodaPlata", metodaPlata);
obj.put("data", getDate(calendarData.getTimeInMillis()));
obj.put("numeVanzator", numeVanzator);
obj.put("numarClient", numarVanzare);
dateJSON.put(obj);
jsonData.put("jsonData", dateJSON.toString());
SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());
} else {
jsonData = new JSONObject(jsonDataFromShared);
dateJSON = jsonData.getJSONArray("jsonData");
obj = new JSONObject();
JSONObject objListaSiModalitate = new JSONObject();
objListaSiModalitate.put("metodaPlata", metodaPlata);
obj.put("produseSelectate", produseSelectate);
obj.put("sumaProduse", pretTotal);
obj.put("data", getDate(calendarData.getTimeInMillis()));
obj.put("numeVanzator", numeVanzator);
obj.put("numarClient", numarVanzare);
dateJSON.put(obj);
jsonData.put("jsonData", dateJSON);
System.out.println("jsonData" + dateJSON);
SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());
}
}
Please help me I have no idea what to idea even if I look over tutorials.
I think your json parsing will be,
try {
JSONObject jsonObject = new JSONObject("jsonData");
JSONObject jsonObject1 = jsonObject.getJSONObject("11-13-2017");
JSONObject jsonObject2 = jsonObject1.getJSONObject("Clau");
JSONArray jsonArray = jsonObject2.getJSONArray("-KyokKjL9UQpsfKZYZqM");
JSONObject jsonObject3 = (JSONObject) jsonArray.getJSONObject(0);
String string = jsonObject3.getString("pret");
String string1 = jsonObject3.getString("produs");
String string2 = jsonObject3.getString("produsId");
} catch (JSONException e) {
e.printStackTrace();
}
Error causes from this line
jsonData.put("jsonData", dateJSON.toString());
Here dateJSON.toString() store the string value to jsonData variable. jsonData is JsonObject.
Then You try to retrieve JsonArray from string
jsonData = new JSONObject(jsonDataFromShared); //This line convert your string to jsonobject.
dateJSON = jsonData.getJSONArray("jsonData");
EDITED
If you want to retreive array from dateJson object
Replace this line
jsonData.put("jsonData", dateJSON.toString());
To
jsonData.put("jsonData", dateJSON);
This question already has answers here:
How can i fix my null pointer exception
(5 answers)
Closed 5 years ago.
I am having troubles with reading a Json file in Java.
this is a Json file with content in this format:
{
"id": "10",
"groups": [{
"name": "text",
"questions": [{
"value": "text"
"response": {
}
}
]}
]}
What I've done in Java:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/test.json"));
JSONObject j = (JSONObject) obj;
System.out.println(j);
String id = (String)j.get("id");
int idpart = Integer.parseInt(id);
System.out.println("id :" + idpart);
JSONArray lg = (JSONArray) j.get("groups");
Iterator i = lg.iterator();
while (i.hasNext()) {
JSONObject gobj = (JSONObject) i.next();
String name = (String)gobj.get("name");
System.out.println(name);
/** The problem start from here !**/
JSONArray lq = (JSONArray) j.get("questions");
Iterator it = lq.iterator();
while (it.hasNext()) {
JSONObject qobj = (JSONObject) i.next();
String idQuestion = (String)qobj.get("id");
System.out.println(idQuestion);
//How to get responses ?
}
}
My question is how to get the response object from questions list?
When I tried to get questions list of object like this:
JSONArray lq = (JSONArray) j.get("questions");
Iterator it = lq.iterator();
while (it.hasNext()) {
JSONObject qobj = (JSONObject) i.next();
String idQuestion = (String)qobj.get("id");
System.out.println(idQuestion);
}
it shows me Error: Null pointer!
Could someone help me?
you have to get questions from lg not from j
you are using Iterator, assigning a group object into gobj so use it:
JSONArray lq = (JSONArray) gobj.get("questions");
I'm currently trying to parse some JSON in my android application but I keep getting an error saying "No value for users"
This is the current code I am using:
JSONObject parentObject = new JSONObject(finalJSON);
JSONObject childObject = new JSONObject(String.valueOf(parentObject));
JSONArray parentArray = childObject.getJSONArray("users");
JSONObject finalObject = parentArray.getJSONObject(0);
String userName = finalObject.getString("username");
String profileLink = finalObject.getString("profileimage");
Log.d("JSON", String.valueOf(finalObject));
return profileimage+ " - " + profileLink ;
and here is my JSON:
{
"reply": {
"users": [
{
"userid": "001",
"loggedIn": 1,
"username": "joe.bloggs",
"profileimage": "http://127.0.0.1/joebloggs.png",
"realname": "Joe Bloggs",
}
]
}
}
Thanks in advance!
You forgot the reply level.
Here is what you should do.
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray userArray = parentObject
.getJSONObject("reply")
.getJSONArray("users");
JSONObject finalObject = userArray.getJSONObject(0);
you can't take new object for object inside object.
you have to do this for parse object inside object.
JSONObject object1 = new JSONObject(finalJSON);
JSONObject object2 = object1.getJSONObject("reply");
JSONArray jsonArray = object2.getJSONArray("users");
JSONObject object3 = jsonArray.getJSONObject(0);
try the following:
JSONObject root = null;
try {
root = new JSONObject("reply");
JSONArray childArray = root.getJSONArray("users");
String userName = childArray.getString(0);
.
.
.
} catch (JSONException e) {
e.printStackTrace();
}
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");
}