简体   繁体   中英

How can I break this Json string in android?

我的 JSON 字符串是:[["Canada", 3], ["SriLanka", 6], ["China", 5], ["UK", 4]]

try {
  JSONArray ja = new JSONArray("[['Canada', 3], ['SriLanka', 6], ['China', 5], ['UK', 4]]");
  for(int i=0;i<ja.length();i++){
    JSONArray ja1 = ja.getJSONArray(i);
    System.out.println("Country Name = "+ja1.get(0));
  }
} catch (JSONException e) {
    e.printStackTrace();
}

This is not standard for JSON. You have to build it this way:

[{"country":"Canada", "x":3}, {"country":"SriLanka", "x":6}, {"country":"China", "x":5}...]

Brackets mean JSONArray

Anyway, if want to split a String.. use Java Basics... It's not an Android issue.

Split by regex and patterns, using split String basic method, or dealing them as a JSONArray..

You can find a lot of information in other posts.

PS: Too long to be a comment.

I hope I would help you.

You can do it like this:

JSONArray array=new JSONArray(jsonString);
    for(int i=0;i<array.length();i++){
     JSONArray array1=array.getJSONArray(i);
     for(int j=0;j<array1.length();j++){
      System.out.print(array1.getString(0));
      System.out.print(array1.getInt(1));
      }
      System.out.println("");
    }

A correct JSON format should be as follows,

[{'name':'Canada', 'value':'3'}, {'name':'SriLanka', 'value':'6'}, {'name': 'China', 'value':'5'}]

Then you can do,

List<Country> list2 = mapper.readValue(jsonString, 
TypeFactory.defaultInstance().constructCollectionType(List.class,  Country.class));

where

Country is,

public class Country {
   private int value;
   private String name;
   //getters and setters
}

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