0

How to read a String into a String array in java , I have the following code :

for (int i=0 ; i<=jArr2.length() ; i++ ) {
    JSONObject jArrOb = jArr2.getJSONObject(i);
    String empIDStr = jArrOb.getString("emp_id");
    String[] plant_ID[i] = empIDStr;             
}

The compiler shows an error stating that String cannot be read into String Array. I am basically moving the values of JSON object into a String Array.

2 Answers 2

2

You need to initialize the String array before the loop:

int n = jArr2.length();
String[] plant_ID = new String[n];

for (int i=0 ; i<n ; i++ )
{
     JSONObject jArrOb = jArr2.getJSONObject(i);
     String empIDStr = jArrOb.getString("emp_id");
     plant_ID[i] = empIDStr; 
                
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try the following where you create the array first. Make sure to change the upper bound of your for loop to avoid an Array out of bounds exception.

String[] plant_ids = new String[jArr2.length];
for (int i=0; i<jArr2.length(); i++ ) {
   JSONObject jArrOb = jArr2.getJSONObject(i);
   String empIDStr = jArrOb.getString("emp_id");
   plant_ids[i] = empIDStr;             
}      

1 Comment

Thank you , it worked.....only modification required in your code was I had to type length() instead of length

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.