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

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

Related

Converting JSONArray to JSONObject [duplicate]

This question already has answers here:
How can I turn a JSONArray into a JSONObject?
(4 answers)
Closed 4 years ago.
I am writing a rest java service. I want to convert my JSONArray to JSONObject and return it. But I am getting "{}" as output when I hit my rest service from browser. Although it is printing fine inside rest service when i tried to print using System.out.println();
PreparedStatement dimDelPS = null;
ResultSet dimDelRS = null;
dimDelPS = connection.prepareStatement("select * from abc");
dimDelRS = dimDelPS.executeQuery();
String dimLow=null;
while (dimDelRS.next()) {
int total_rows = dimDelRS.getMetaData().getColumnCount();
for (int i = 0; i < total_rows; i++) {
org.json.JSONObject obj = new org.json.JSONObject();
obj.put(dimDelRS.getMetaData().getColumnLabel(i + 1)
.toLowerCase(), dimDelRS.getObject(i + 1));
jsonArray.put(obj);
}
}
System.out.println("json1 :"+jsonArray);
//Sample output at this stage: ["{\"employee\":\"ANTHONY.DUNNE\"}","{\"type\":\"Manager\"}"]
dimDelRS.close();
dimDelPS.close();
JSONObject jsobobject= new JSONObject();
jsobobject.put("aoColumnDefs",jsonArray);
System.out.println(jsobobject);
return jsobobject;
You can't just return JSONObject.
You need to male sure you Marshall it into json.
'return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).build();'
Browser understand String, and not java object.

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

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

How to parse a JSONArray of JSONObjects in JAVA?

I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling

Json Array not properly generated

I have written java code for generating json of my searched data from file.But its not generating exact JsonArray. Its like
[{"item":"1617"},{"item":"1617"}]
instead of
[{"item":"747"},{"item":"1617"}].
Here 1617 is last item which is fetched from file.
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID);
if(j == userId) {
itemid = products.get("item");
jo.put("item",itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
you are actually creating one jSONobject object to handle two objects, shouldn't you need to create JSONObjects in the while loop? something like this, so every iteration in while loop will create a new JSONObject and add it to JSONArray
JSONArray ja = new JSONArray();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID, 10);
if(j == userId)
{
JSONObject jo = new JSONObject();
itemid = products.get("item");
jo.put("item", itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
Extra:
i am not sure how java does conversion for string to integer, but i think you should always specify radix when using parseInt so the strings like '09' will not be treated as octal value and converted to wrong value (atleast this is true in javascript :))
Integer.parseInt(productID, 10);
You must re-instantiate your JSonObject inside the loop because when you modify it you modify the underlying object which is referenced several times by your array. Move your JSONObject jo = new JSONObject(); inside the loop and it should work fine.
Place JSONObject jo = new JSONObject(); inside the loop:
while (products.readRecord())
{
JSONObject jo = new JSONObject();
String productID = products.get("user");
int j = Integer.parseInt(productID);
// etc
}

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