简体   繁体   中英

How to convert json object to string array

I have got a null String variable and String array is stock string variable like this:

String value1;
String value2;

String[] arr = {value1,value2};

And in JSON object I try coding like this:

for(int i=0;i < jLocation.length();i++){
    value1 = jLocation.getJSONObject(i).getString("name");
    value2 = jLocation.getJSONObject(i).getString("location");
} 

But not return value into variable. How to resolve problem?

Look like you want to store name and location in an array, if yes then

for(int i=0; i < jLocation.length(); i++){
    arr[0] = jLocation.getJSONObject(i).getString("name");
    arr[1] = jLocation.getJSONObject(i).getString("location");
} 

Note - This code assume that you only have one name and location. However I sugegst you to do something like below:

Create a Location class, eg below

public class Location {
    private String name;
    private String location;

    public Location(String name, String location) {
        this.name = name;
        this.location = location;
    }

    public String getName() {
        return name;
    }

    public String getLocation() {
        return location;
    }
}

Then use it like below:

public static void main(String[] args) {
        List<Location> locations = new ArrayList<Location>();

        for(int i=0; i < jLocation.length(); i++){
            String name = jLocation.getJSONObject(i).getString("name");
            String location = jLocation.getJSONObject(i).getString("location");

            locations.add(new Location(name, location));
        } 
    }

Try this

//First initiate string
String value1;
String value2;

//Read json
for(int i-0;i < jLocation.length();i++){
    value1 = jLocation.getJSONObject(i).getString("name");
    value2 = jLocation.getJSONObject(i).getString("location");
} 

//Create Stting array
String[ ] arr = {value1,value2};

It will use to add only one value to array.

I prefer ArrayList . Then you can add all the data to ArrayList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM