How to Read JSON From File in Java - json.simple [duplicate] - java

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");

Related

I want to extract the value from JSON by same id one id using java

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"}

How can I control a empty JsonArray, if string is " [ ] " [duplicate]

This question already has answers here:
how to check if a JSONArray is empty in java?
(4 answers)
Closed 5 years ago.
my json string is
String RESPONSE = " { "Table": [] } ";
and I use
JSONObject jsonObj = new JSONObject(RESPONSE);
JSONArray contacts = jsonObj.getJSONArray("Table");
Therefore, contacts = [] I mean empty.
How can I control that array is empty.
After this controller I use this command
JSONObject c = contacts.getJSONObject(0);
Of course is not empty :)
You can use length function:
JSONObject jsonObj = new JSONObject(RESPONSE);
JSONArray contacts = jsonObj.getJSONArray("Table");
if(contacts.length() > 0 ) {
JSONObject c = contacts.getJSONObject(0);
}
You could use the isNull() function.
JSONObject jsonObj = new JSONObject(RESPONSE);
JSONArray contacts = jsonObj.getJSONArray("Table");
if(!contacts.isNull(0)) {
JSONObject c = contacts.getJSONObject(0);
}

Iterator throwing NullPointerException inside JSONArray null value

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

Parse JSON object to string in java

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");
}
}

Getting JSONObject from JSONArray [duplicate]

This question already has answers here:
Accessing members of items in a JSONArray with Java
(6 answers)
Closed 6 years ago.
I am in a bit of a fix regarding the JSONObject that I am getting as a response from the server.
jsonObj = new JSONObject(resultString);
JSONObject sync_reponse = jsonObj.getJSONObject("syncresponse");
String synckey_string = sync_reponse.getString("synckey");
JSONArray createdtrs_array = sync_reponse.getJSONArray("createdtrs");
JSONArray modtrs_array = sync_reponse.getJSONArray("modtrs");
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
String deleted_string = deletedtrs_array.toString();
{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]
as you can see in the response that I am getting I am parsing the JSONObject and creating syncresponse, synckey as a JSON object createdtrs, modtrs, deletedtrs as a JSONArray. I want to access the JSONObject from deletedtrs, so that I can split them apart and use the values. i.e I want to extract companyid, username, date etc.
How can I go about this ?
Thanks for your input.
JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:
JSONArray array;
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// do some stuff....
}
Here is your json:
{
"syncresponse": {
"synckey": "2011-09-30 14:52:00",
"createdtrs": [
],
"modtrs": [
],
"deletedtrs": [
{
"companyid": "UTB17",
"username": "DA",
"date": "2011-09-26",
"reportid": "31341"
}
]
}
}
and it's parsing:
JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
JSONObject object3 = jArray3.getJSONObject(i);
String comp_id = object3.getString("companyid");
String username = object3.getString("username");
String date = object3.getString("date");
String report_id = object3.getString("reportid");
}
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
for(int i = 0; deletedtrs_array.length(); i++){
JSONObject myObj = deletedtrs_array.getJSONObject(i);
}
{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]
The get companyid, username, date;
jsonObj.syncresponse.deletedtrs[0].companyid
jsonObj.syncresponse.deletedtrs[0].username
jsonObj.syncresponse.deletedtrs[0].date
start from
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each deletedtrs_array member
Iterating
for(int i = 0; i < deletedtrs_array.length(); i++){
JSONObject obj = deletedtrs_array.getJSONObject(i);
Log.d("Item no."+i, obj.toString());
// create object of type DeletedTrsWrapper like this
DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);
// String company_id = obj.getString("companyid");
// String username = obj.getString("username");
// String date = obj.getString("date");
// int report_id = obj.getInt("reportid");
}
Own object type
class DeletedTrsWrapper {
public String company_id;
public String username;
public String date;
public int report_id;
public DeletedTrsWrapper(JSONObject obj){
company_id = obj.getString("companyid");
username = obj.getString("username");
date = obj.getString("date");
report_id = obj.getInt("reportid");
}
}
When using google gson library.
var getRowData =
[{
"dayOfWeek": "Sun",
"date": "11-Mar-2012",
"los": "1",
"specialEvent": "",
"lrv": "0"
},
{
"dayOfWeek": "Mon",
"date": "",
"los": "2",
"specialEvent": "",
"lrv": "0.16"
}];
JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
JsonArray jsonArray = root.getAsJsonArray();
JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject();
String dayOfWeek = jsonObject1.get("dayOfWeek").toString();
// when using jackson library
JsonFactory f = new JsonFactory();
ObjectMapper mapper = new ObjectMapper();
JsonParser jp = f.createJsonParser(getRowData);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT) {
Map<String,Object> userData = mapper.readValue(jp, Map.class);
userData.get("dayOfWeek");
// process
// after binding, stream points to closing END_OBJECT
}
Make use of Android Volly library as much as possible. It maps your JSON reponse in respective class objects. You can add getter setter for that response model objects. And then you can access these JSON values/parameter using .operator like normal JAVA Object. It makes response handling very simple.

Categories