Kirti
Kirti

Reputation: 701

How to split this kind of data in android

Here is the

  string  one =[{"ID":5,"Name":"Sai"}]

how i get only id and name from this string

  Matcher matcher = Pattern.compile("\\[([^\\]]+)").matcher(one);

                    List<String> tags = new ArrayList<String>();

                    int pos = -1;
                    while (matcher.find(pos+1)){
                        pos = matcher.start();
                        tags.add(matcher.group(1));
                    }

                    System.out.println("getting data"+tags);

i tried this but it didn't work

Upvotes: 0

Views: 186

Answers (5)

Imtiyaz Khalani
Imtiyaz Khalani

Reputation: 2053

it is a json formate Date use JsonObject class to parse this data tutorial this

    JSONArray jsonArray = new JSONArray("[{\"ID\":5,\"Name\":\"Sai\"}]");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject object = jsonArray.getJSONObject(i);
        System.out.println(object.getString("ID"));
        System.out.println(object.getString("Name"));
    }

Upvotes: 1

Umer Farooq
Umer Farooq

Reputation: 7486

It's JSON format and it can very easily be read in Android. Here is the sample code:

            JSONArray array = new JSONArray(one);



            int length = array.length();

            for(int i=0;i< length; i++)
            {
                JSONObject temp = array.getJSONObject(i);

                System.out.println(temp.getString("ID"));

                System.out.println(temp.getString("Name")); 

            }

Upvotes: 2

Digvesh Patel
Digvesh Patel

Reputation: 6533

List<String> ls = new ArrayList<String>(one);
                    JSONArray array = new JSONArray();
            for(int i = 0; i< array.length(); i++){
                JSONObject obj = array.getJSONObject(i);
                 ls.add(obj.getString("Name"));

            }

Upvotes: 2

Paresh Mayani
Paresh Mayani

Reputation: 128428

First of all, your string initialization is wrong.

Wrong:

string  one =[{"ID":5,"Name":"Sai"}]

Correct:

String  one ="[{\"ID\":5,\"Name\":\"Sai\"}]";

Second, its a JSON formatted data so you can parse it using JSONArray and JSONObject classes, instead of creating any pattern.

Now, in your case its JSONObject inside JSONArray so initially create an object of JSONArray using your string.

For example:

  JSONArray arrayJSON = new JSONArray(one);   // 'one' is your JSON String
    for(int i=0; i<arrayJSON.length(); i++) {
         JSONObject objJson = arrayJSON.getJSONObject(i);
         String ID = objJson.getString("ID");
         .....
         .....
          // same way you can fetch/parse any string/value from JSONObject/JSONArray

    }

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44834

This format of data is called JSON.

Have a look at Go to http://json.org/, scroll to (almost) the end, click on one of the many Java libraries listed.

Upvotes: 1

Related Questions