解析json数组

来源:互联网 发布:浪登西装 怎么样 知乎 编辑:程序博客网 时间:2024/06/05 01:02
package animtest.com.example.e531.arrayjsontest_demo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

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

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

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

        List<Result> datas=new ArrayList<>();

        try {
            //打开assets中的文件
            InputStream inputStream=getAssets().open("array.json");
            String str=StreamToString.streamToStr(inputStream,"utf-8");

          /*
          //第一种:gson解析  利用type
          //获取集合数据的type
            Type type= new TypeToken<List<Result>>(){}.getType();

            Gson gson=new Gson();
            datas=gson.fromJson(str,type);

            Log.d("zzz",datas.size()+"---");
            for(Result r:datas){
                Log.d("zzz",r.toString());
            }*/

         /*
         //第二种:原生解析
         try {
                JSONArray array=new JSONArray(str);
                for(int i=0;i<array.length();i++){
                    Result result=new Result();
                    JSONObject obj=array.optJSONObject(i);
                    String img3=obj.optString("img3");
                    String name=obj.optString("name");
                    double price=obj.optDouble("price");
                    double tgprice=obj.optDouble("tg_price");

                    result.setImg3(img3);
                    result.setName(name);
                    result.setPrice(price);
                    result.setTg_price(tgprice);

                    datas.add(result);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }*/


            //混合解析
            try {
                Gson gson=new Gson();

                JSONArray array=new JSONArray(str);

                for(int i=0;i<array.length();i++){
                    JSONObject object=array.optJSONObject(i);
                    Result r=gson.fromJson(object.toString(),Result.class);
                    datas.add(r);
                }


            } catch (JSONException e) {
                e.printStackTrace();
            }


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

    }
}