0

As this question has been closed before actual answer for this specific problem has been found, it is here.

In java, I am using the simplejson library to handle json.

My json have this structure (truncated):

{

    "assembling-tags": {
        "list": [
            "G_StaticCushion_R",
            "G_CommutationPosition_R",
            "G_PlastificationPlasticisingDuration_R",
            "G_PlastificationScrewPositionAfter_R",
            "G_CommutationPressure_R",
            "G_DynamicCommutationDuration_R",
            "G_DynamicLockingToolDuration_R",
            "G_CycleTime_R",
            "CYCLE_TIME",
            "G_ClosureSecurityClosingToolDuration_R"
        ]
    },

I read the json data with the following code:

try (FileReader reader = new FileReader(
                "/home/hduser/eclipse-workspace/db-simulatiob/src/generator-config.json")) {

            JSONObject obj = (JSONObject) jsonParser.parse(reader);

And I am trying to convert the list json array into a string array, with the following:

String[] aTag = (String[]) ((JSONObject) obj.get("assembling-tags")).get("list");

But this throws the following exception:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to [Ljava.lang.String;

How can I convert the json array into a string array (String[]) ?

Itération 122442
  • 2,644
  • 2
  • 27
  • 73

1 Answers1

0

Use below code, Hopefully it will solved your problem:

String jstr = "{\r\n" + 
                "\r\n" + 
                "    \"assembling-tags\": {\r\n" + 
                "        \"list\": [\r\n" + 
                "            \"G_StaticCushion_R\",\r\n" + 
                "            \"G_CommutationPosition_R\",\r\n" + 
                "            \"G_PlastificationPlasticisingDuration_R\",\r\n" + 
                "            \"G_PlastificationScrewPositionAfter_R\",\r\n" + 
                "            \"G_CommutationPressure_R\",\r\n" + 
                "            \"G_DynamicCommutationDuration_R\",\r\n" + 
                "            \"G_DynamicLockingToolDuration_R\",\r\n" + 
                "            \"G_CycleTime_R\",\r\n" + 
                "            \"CYCLE_TIME\",\r\n" + 
                "            \"G_ClosureSecurityClosingToolDuration_R\"\r\n" + 
                "        ]\r\n" + 
                "    }}";

        JSONObject obj  = new JSONObject(jstr);
        JSONArray jarr = obj .getJSONObject("assembling-tags").getJSONArray("list");
        String[] aTag =new String[jarr.length()];
        for(int i=0; i<aTag.length; i++) {
            aTag[i]=jarr.optString(i);
        } // aTag is ready to use 

        // Here I just print the output
        for(int i=0; i<aTag.length; i++) {
            System.out.println("jsonArray to String array:"+aTag[i]); 
        }

Also import below:

import org.json.JSONArray;
import org.json.JSONObject;
shahaf
  • 4,750
  • 2
  • 29
  • 32