Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

java - How to parse Sub JSONArray and display image?

I am a php programmer and I am trying to learn JAVA. I have problem trying to parse a json file. It's been for 3 days..having a headache at this. I am create an android application (using JAVA) to parse json file. This is the sample json data (http://metalgearrisingguide.com/samplejson.json) And how to display the image?

When i tried, I have the following error at my logcat and nothing is displayed on the emulator

Error parsing data org.json.JSONException: Value {"product":[{"summary":"Speak a word and the knob will turn by itself","state":"good","image":"http://upload.wikimedia.org/wikipedia/commons/e/e9/Door_Knob_with_Lock_USA.jpg","title":"Special Door knob requires no holding just music","address":[{"address":"Merchant address 1"},{"address":"merchant address 2"}],"url":"http://merchantwebsite.com"},{"summary":"This door bell will detect faces of known people and change music if unknown","state":"good","image":"http://www.thedoorbell.net/images/DoorbellHeader.jpg","title":"Special Door Bell that uses face recognition technology","address":[{"address":"Merchant address 1"},{"address":"merchant address 2"}],"url":"http://merchantwebsite2.com"},{"summary":"Can't wake up in the morning?
Will you be awake for party? Listen to your favourite song that will awake you!","state":"refurnished","image":"http://jgrundig.wpengine.netdna-cdn.com/wp-content/uploads/2011/08/RCA-Alarm-Clock-with-Charging-Cord-RC107.jpg","title":"The only alarm clock that plays your favourite song from your smartphone","address":[{"address":"Merchant address 1"},{"address":"merchant address 2"}],"url":"http://merchantwebsite3.com"}],"site":{"sitename":"Simple Product Find","imgprefix":"http://mydomain.com/","urlprefix":"http://mydomain.com/"}} at data of type org.json.JSONObject cannot be converted to JSONArray

Here is my JSONfunctions class:

public class JSONfunctions {
    public static JSONObject getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }

      //convert response to string
        try{
                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 + "
");
                }
                is.close();
                result=sb.toString();



        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }


        try{

            jArray = new JSONObject(result);            
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }


        return jArray;
        //return result;
    }
}

And here is my code:

public class Main extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


        JSONObject json = JSONfunctions.getJSONfromURL("http://metalgearrisingguide.com/samplejson.json");


        try{

            JSONArray data = json.getJSONArray("data");
            JSONArray products = data.getJSONArray(1);

           for(int i=0;i<products.length();i++){    

                HashMap<String, String> map = new HashMap<String, String>();    
                JSONObject e = products.getJSONObject(i);

                map.put("id",  String.valueOf(i));
                map.put("title", "Product name:" + e.getString("title"));
                        map.put("state", "Condition:" + e.getString("state"));
                map.put("summary", "Description: " +  e.getString("summary"));
                mylist.add(map);




                Set set = map.entrySet(); 
                // Get an iterator 
                Iterator o = set.iterator(); 
                // Display elements 
                while(o.hasNext()) { 
                Map.Entry me = (Map.Entry)o.next(); 
                System.out.print(me.getKey() + ": "); 
                System.out.println(me.getValue()); 
                } 
                System.out.println(); 

            }

        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }





        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
                        new String[] { "state", "summary" }, 
                        new int[] { R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 
            }
        });


    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You ark two questions, the first, how to parse the sub json; second, how to display image from the net; I made a successful demo by your sample json url as follows:

First, define a data class: Data.java

    package com.example.jsonparser;

import java.util.ArrayList;

public class Data {

    private String mState;
    private String mImageUrl;
    private String mTitle;
    private String mSummary;
    private ArrayList<String> mAddList;
    private String mUrl;

    public Data(String mState, String mImageUrl, String mTitle,
            String mSummary, ArrayList<String> addList, String mUrl) {
        super();
        this.mState = mState;
        this.mImageUrl = mImageUrl;
        this.mTitle = mTitle;
        this.mSummary = mSummary;
        this.mAddList = addList;
        this.mUrl = mUrl;
    }

    public String getmState() {
        return mState;
    }

    public void setmState(String mState) {
        this.mState = mState;
    }

    public String getmImageUrl() {
        return mImageUrl;
    }

    public void setmImageUrl(String mImageUrl) {
        this.mImageUrl = mImageUrl;
    }

    public String getmTitle() {
        return mTitle;
    }

    public void setmTitle(String mTitle) {
        this.mTitle = mTitle;
    }

    public String getmSummary() {
        return mSummary;
    }

    public void setmSummary(String mSummary) {
        this.mSummary = mSummary;
    }

    public ArrayList<String> getmAddress1() {
        return mAddList;
    }

    public void setmAddress1(ArrayList<String> mAddress1) {
        this.mAddList = mAddress1;
    }

    public String getmUrl() {
        return mUrl;
    }

    public void setmUrl(String mUrl) {
        this.mUrl = mUrl;
    }

}

Second, define a parser class for parsing the json string: Parser.java

 package com.example.jsonparser;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class Parser {

    private ArrayList<Data> mDataSource = new ArrayList<Data>();

    public Parser(String json) {
        jsonParser(json);
    }

    private void jsonParser(String json) {

        try {

            JSONObject obj = new JSONObject(json);
            JSONObject var = obj.getJSONObject("data");


            JSONArray list = var.getJSONArray("product");

            int len  = list.length();
            for (int i = 0; i < len; i++) {
                try {
                    JSONObject data = list.getJSONObject(i);
                    String state = data.getString("state");
                    String image = data.getString("image");
                    String title = data.getString("title");
                    String summary = data.getString("summary");
                    String url = data.getString("url");
                    ArrayList<String> addList = new ArrayList<String>();
                    JSONArray addArray = data.getJSONArray("address");
                    int size = addArray.length();
                    /**
                     * parser sub json
                     */
                    for(int j = 0; j < size; j++) {
                        addList.add(addArray.getJSONObject(j).getString("address"));
                    }
                    mDataSource.add(new Data(state, image, title, summary, addList, url));

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public ArrayList<Data> getSource() {
        return mDataSource;
    }
}

Third, define a task download image by url: DownloadImageTask.java

    package com.example.jsonparser;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class DownloadImageTask extends AsyncTask<Void, Void, Bitmap> {

    private String mUrl;
    private ImageView mImageView = null;

    public DownloadImageTask(String Url, ImageView imageView) {

        mUrl = Url;
        this.mImageView = imageView;
    }

    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        if (result != null) {
            mImageView.setImageBitmap(result);
        }
    }

    protected Bitmap doInBackground(Void... params) {

        Bitmap bitmap = getBitmap(mUrl);
        return bitmap;
    }

    public Bitmap getBitmap(String imageUrl) {
        Bitmap mBitmap = null;
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream is = conn.getInputStream();
            mBitmap = BitmapFactory.decodeStream(is);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return mBitmap;
    }
}

Forth, define a adapter extend BaseAdapter for displaying the data and image: Adapter.java

    package com.example.jsonparser;

import java.util.ArrayList;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.RecyclerListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class Adapter extends BaseAdapter {

    private static final String TAG = "Adapter";
    private Activity mActivity;
    public ArrayList<Data> mObjects;

    static class ViewHolder {
        ImageView icon;
        TextView title;
        DownloadImageTask mTask;
    }

    public Adapter(Activity activity, ArrayList<Data> mObjects) {

        this.mActivity = (Activity) activity;
        this.mObjects = mObjects;
    }

    public void setObjects(ArrayList<Data> mObjects) {
        this.mObjects = mObjects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Data item = mObjects.get(position);
        View rowView = convertView;

        if (rowView == null) {
            LayoutInflater inflater = mActivity.getLayoutInflater();
            rowView = inflater.inflate(R.layout.item, parent, false);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.icon = (ImageView) rowView.findViewById(R.id.image);
            viewHolder.title = (TextView) rowView.findViewById(R.id.title);
            rowView.setTag(viewHolder);
        }

        ViewHolder holder = (ViewHolder) rowView.getTag();

        holder.title.setText(item.getmTitle());
        holder.icon.setBackgroundResource(R.drawable.ic_launcher);
        holder.mTask = new DownloadImageTask(item.getmImageUrl(), holder.icon);
        if (!holder.mTask.isCancelled()) {
            holder.mTask.execute();
        }

        return rowView;
    }

    @Override
    public int getCount() {

        return (this.mObjects.size());
    }

    @Override
    public Object getItem(int position) {

        return (this.mObjects.get(position));
    }

    @Override
    public long getItemId(int position) {

        return (position);
    }

    public AbsListView.RecyclerListener mRecyclerListener = new RecyclerListener( ){

        public void onMovedToScrapHeap(View view) {
            ViewHolder viewHolder = (ViewHolder) view.getTag();
            DownloadImageTask imagetask = viewHolder.mTask;
            if (imagetask != null) {
                imagetask.cancel(true);
            }
        }

    };
}

The last, use these class in activity: MainActivity.java

    package com.example.jsonparser;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;

public class MainActivity extends Activity {

    private ListView mListView;
    private Adapter mAdapter;
    private ArrayList<Data> mSource = new ArrayList<Data>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mListView = (ListView) findViewById(android.R.id.list);
        mAdapter = new Adapter(this, mSource);
        mListView.setAdapter(mAdapter);
        mListView.setRecyclerListener(mAdapter.mRecyclerListener);

        final String url = "http://metalgearrisingguide.com/samplejson.json";
        new Thread(new Runnable() {

            @Override
            public void run() {
                Parser parser = new Parser(getJSONfromURL(url));
                mSource = parser.getSource();
                Message msg = mHandler.obtainMessage();
                mHandler.sendMessage(msg);

            }
        }).start();

    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            mAdapter.setObjects(mSource);
            mAdapter.notifyDataSetChanged();
        }
    };

    public String getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";

        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // convert response to string
        try {
            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 + "
");
            }
            is.close();
            result = sb.toString();

        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        return result;
    }
}

activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:cacheColorHint="@android:color/transparent" />

</LinearLayout>

item.xml


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...