1

I am working on one requirement , where I need to get the length of below json and length of filters object in the entire json

attaching the json for refrence.

{
    "employeeId": "41825",
    "userId": "tawright",
    "sourceSystem": "Visibility",
    "loginId": "nudayaku",
    "groupBy": "order",
    "isPretty": false,
    "limit": 10,
    "offset": 0,
    "sortBy": "so_date",
    "sortOrder": "desc",
    "filters": [{
        "name": "type",
        "value": "POS",
        "op": "eq"
    }],
    "srpGoalHeaderId": 3069181,
    "srpGoalQuotaId": 1750558,
    "category": "PRD & SVC|AG",
    "goalSheet": "2020 CS020        28-Jul-2019 to 25-Jul-2020",
    "loggedInUser": "nudayaku",
    "requestedScreen": "orderSearch.g2c"
}

Can some one help me how can i get the Length of the filters involved in this JSon.

I am getting the below error while i am parsing the JSOn

org.json.simple.JSONArray cannot be cast to org.json.JSONArray

import java.io.FileOutputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.sql.Timestamp;


import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.json.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.cisco.export.utils.SFDbConnection;
import com.fasterxml.jackson.core.JsonParser;


            //Assign value from Input Export JSon

            JSONObject json = getJSONObject(getFilters());
            String employeeId = (String) json.get("employeeId");
            Long planId = (Long) json.get("planId");
            Long srpGoalHeaderId = (Long) json.get("srpGoalHeaderId");
            Long allocationId = (Long) json.get("allocationId");
            String nodeName = (String) json.get("nodeName");
            String erpPosFlag = (String) json.get("erpPosFlag");
            Long soNumber = (Long) json.get("soNumber");
            ObjectMapper mapper = new ObjectMapper();
            JSONArray filters = (JSONArray) json.get("filters");

            System.out.println("filters" +filters);

error log:

Exception is  java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.JSONArray java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.JSONArray

Thanks, Nikhil

3
  • It would be helpful to post the Java code in question, since that's what's throwing the exception, don't you think? Make sure to include the import statements, and make sure you cut and paste the exact error message in full rather than typing it from memory, because if the error message you included originally is correct, your solution is likely to be more esoteric than similar messages. Commented Jun 9, 2020 at 2:58
  • Hi Mars, i have updated the import statement as well as the java code with import and where json changes how i am doing it Commented Jun 9, 2020 at 3:10
  • 1
    Change import org.json.JSONArray; to import org.json.simple.JSONArray; and try again. Commented Jun 9, 2020 at 3:19

6 Answers 6

2

You are importing JSONArray as below (from a different library)

import org.json.JSONArray;

Import it from json simple as well

import org.json.simple.JSONArray;

Hope this helps !!

Sign up to request clarification or add additional context in comments.

Comments

0

try mapping it into an object and you could get the filters length pretty easily. eg

var object = {
          "employeeId": "41825",
          "userId": "tawright",
          "sourceSystem": "Visibility",
          "loginId": "nudayaku",
          "groupBy": "order",
          "isPretty": false,
          "limit": 10,
          "offset": 0,
          "sortBy": "so_date",
          "sortOrder": "desc",
          "filters": [{
              "name": "type",
              "value": "POS",
              "op": "eq"
          }],
          "srpGoalHeaderId": 3069181,
          "srpGoalQuotaId": 1750558,
          "category": "PRD & SVC|AG",
          "goalSheet": "2020 CS020        28-Jul-2019 to 25-Jul-2020",
          "loggedInUser": "nudayaku",
          "requestedScreen": "orderSearch.g2c"
    }

console.log('filters length',object.filters.length);


to parse the json into object use JsonParser e.g.

JSONParser parse = new JSONParser();
Object EmployeeObject = parse.parse(yourjsonobject);

console.log(EmployeeObject.filters.length);

Comments

0

The length of the "filters" jsonArray is actually 1 because within the square [] brackets you have {} which is accounted as 1 element in the array.

Assuming you want to get the size of the json object inside the json array i.e

{ "name": "type", "value": "POS", "op": "eq" }

you need to iterate through the object to get the size

5 Comments

yes, i need to take the count of filters in an array like the below example .
"filters": [{ "name": "booking", "value": "0", "op": "neq" }, { "name": "type", "value": "Direct", "op": "eq" }],
here the number of filters is 2
i am not sure how can i get the number of filters in a json
use something like this JSONObject obj = new JSONObject(<Your json object>); org.json.JSONArray jsonArray = obj.getJSONArray("filters");
0

You're mixing two incompatible libraries of json processing, hence the error.

From your code snippet:

import org.json.JSONArray;
import org.json.simple.JSONObject;

Obviously its wrong:

org.json.simple is offered by http://code.google.com/p/json-simple/

org.json is supported by some other libraries like this one for instance

The best would be opening the corresponding classes and checking out to which jar they actually belong (for example, in IntelliJ you can simply press Alt + F1 for this).

So stick to one library and it should work.

Comments

0

Instead of mixing two different library operations which are wrong indeed, you can make use of the same ObjectMapper which you are creating to get the filters list

ObjectMapper mapper = new ObjectMapper();

Using the above mapper convert your json to a Map<String, Object>, and then you can have handle on the entire json. You can do something like this to get the list out of your json.

Map<String, Object> map = mapper.readValue(json, Map.class);
        if(map.containsKey("filters")) {
            List<Object> filters = (List) map.get("filters");
            System.out.println(filters);
            System.out.println(filters.size());
        }

This snippets prints out:

[{name=type, value=POS, op=eq}]
1

Comments

0

I solve it that way myJson ->My Json that inside it exist an array

fieldPath -> the path to the array

import com.jayway.jsonpath.JsonPath;
import org.json.JSONArray;
import org.json.simple.JSONObject;

JSONObject myJson;

    public long CountFields(String fieldPath) {
      String onlyMyArray=JsonPath.parse(myJson).read(fieldPath).toString();
      JSONArray jsonArray = new JSONArray(onlyMyArray);
      return jsonArray.length();
                       }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.