Himanshu
Himanshu

Reputation: 881

How to formate Json data that comes from php in android?

i have following php file....

    mysql_connect("localhost","root","");
    mysql_select_db("database_name");
    $sql=mysql_query("select * from members");
    while($row=mysql_fetch_assoc($sql)) $output[]=$row;
    print(json_encode($output));
    mysql_close();
     ?>

with this i get all that data in android following is my android content,

        BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }

    is.close();
    String json = sb.toString();

i have get json as a string. From android but now i want use that data in listview. I can't understand how can i use it. Please give me some idea or suggestions.

Upvotes: 0

Views: 127

Answers (3)

Ben Weiss
Ben Weiss

Reputation: 17940

The JSON package within Android provides you with the required classes.

You can easily create a JSONObject with your data like so:

JSONObject jsonObject = new JSONObject(json);

If you have a JSONArray you can do the same with the JSONArray class:

JSONArray jsonArray = new JSONArray(json);

The source of your JSON is not relevant as long as it's valid JSON.

You need to create your model classes within Java and provide the parsed JSON data to the models. These can then be used for displaying the content within your ListView.

Upvotes: 1

Chirag
Chirag

Reputation: 56925

Parse Data from Json and Save it in ArrayList and set that arrayList to Listview.

You can create Json object from String like below.

JSONObject jsonObject = new JSONObject(json);

You can create Json Array object from String like below.

JSONArray ja = new JSONArray(json);

Look at this Tutorial .

Upvotes: 2

Infinity
Infinity

Reputation: 3875

I am highly recommend GSON library to serialize your json string into java object. You can get the GSON package here http://code.google.com/p/google-gson/

Once you added GSON to your android build path, the rest is trivial. Parsing from json string to java object is as simple as this,

gsonObject.fromJson("JSON STRING", ObjectModel.class);

More on Gson api is available here

https://sites.google.com/site/gson/gson-user-guide

Upvotes: 1

Related Questions