java JSON 数组解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7347318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:36:23  来源:igfitidea点击:

JSON Array Parse

java

提问by Gablu

How to parse a JSON Array,Suppose we have an array given below,how to parse this array in Java,please help me with a code.

如何解析一个 JSON 数组,假设我们有一个下面给出的数组,如何在 Java 中解析这个数组,请帮我写一段代码。

[{"guild": "Crimson", "region": "us", "realm": "Caelestrasz", "timestamp": 1311860040}, {"guild": "Crimson", "region": "us", "realm": "Caelestrasz", "timestamp": 1311511740}]

回答by Sahil Muthoo

String gameJSON = "[{\"guild\": \"Crimson\", \"region\": \"us\", \"realm\": \"Caelestrasz\", \"timestamp\": 1311860040}, {\"guild\": \"Crimson\", \"region\": \"us\", \"realm\": \"Caelestrasz\", \"timestamp\": 1311511740}]";
JSONArray array = new JSONArray(gameJSON);
for (int i = 0; i < array.length(); i++) {
    System.out.println(array.getJSONObject(i));
}
// Access by key : value
for (int i = 0; i < array.length(); i++) {
    JSONObject element = array.getJSONObject(0);
    System.out.format("Player #%d: Realm = %s, Guild = %s\n"
                          , i + 1, element.get("realm"),element.get("guild"));

}

Sample code using the JSON.orglib.

使用JSON.org库的示例代码。

回答by hamid azhdari

First of all you must have model how to make it ! for example we have 3 object like id , name and family you create a class and name it like

首先你必须有模型如何制作!例如,我们有 3 个对象,如 id 、 name 和 family 您创建一个类并将其命名为

model_phpservice


public class model_phpservice {
    private int id;
    private String name;
    private String family;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFamily() {
        return family;
    }

    public void setFamily(String family) {
        this.family = family;
    }
}

after that you must have write a code to parse the codes we name this class

之后你必须编写一个代码来解析我们命名这个类的代码

phpservices


public class phpservices {
    private final Context context;
    private static final String TAG = "phpservices";

    public phpservices(Context context) {
        this.context = context;
    }

    public void jsonrequest(final InterFaceData interFaceData) {
    JsonArrayRequest jsonArrayRequest = new
            JsonArrayRequest(Request.Method.GET, "http://yourip/youraddress/",
            null, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

            List<model_phpservice> CompleteList=new ArrayList<>();
            for (int i = 0; i < response.length(); i++) {
                model_phpservice getmydata=new model_phpservice();
                try{

            JSONObject jsonObject = response.getJSONObject(i);
            getmydata.setId(jsonObject.getInt("id")) ;
            getmydata.setName(jsonObject.getString("name"));
            getmydata.setFamily(jsonObject.getString("family"));
                }catch (JSONException e) {
                    e.printStackTrace();
                    Log.e(TAG, "getdata: "+"getdata errrorrrr" );
                }
            CompleteList.add(getmydata);

        }



            if (CompleteList!=null) {
                Log.i(TAG, "onResponse: " + "itsok");

                interFaceData.oninterface(CompleteList);
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.e(TAG, "onErrorResponse: "+"not ok" );
        }
    });


        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(8000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        RequestQueue requestQueue=Volley.newRequestQueue(context);

        requestQueue.add(jsonArrayRequest);

}

    public interface InterFaceData{
        void oninterface(List<model_phpservice> listtosend);
    }
}

i know maybe its hard to understand but that the correct code

我知道可能很难理解,但正确的代码

http://yourip/youraddress/ 

you must put your page address that gives you the json code for ip if you test your app in emulator you can find the ip with ipconfig in cmd

如果您在模拟器中测试您的应用程序,您必须输入您的页面地址,该地址为您提供 ip 的 json 代码,您可以在 cmd 中使用 ipconfig 找到该 ip

and for interface i use it , we need interface to send the list to main activity

对于我使用的界面,我们需要界面将列表发送到主要活动

and in main activity

并在主要活动中

public class phpservicesActivity extends AppCompatActivity{
    private static final String TAG = "phpservicesActivity";
    private Button   btn_get;
    private ListView listView;
   // private ProgressBar progress;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phpservices);

        btn_get=(Button)findViewById(R.id.btn_get);
        listView=(ListView)findViewById(R.id.list_data);
       //progress=(ProgressBar)findViewById(R.id.progress3);


         final phpservices servicesss=new phpservices(this);

         btn_get.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
             // progress.setVisibility(View.VISIBLE);
              servicesss.jsonrequest(new phpservices.InterFaceData() {
                  @Override
                  public void oninterface(List<model_phpservice> completelist) {
                      if (listtosend!=null)
                      {
                          Log.i(TAG, "oninterface: "+"interface is ok");

                          adapterff adapter =new adapterff(phpservicesActivity.this,completelist);

                          listView.setAdapter(adapter);

                      }
                      else{
                          Log.e(TAG, "oninterface: "+"error in main activity" );

                      }
                     //progress.setVisibility(View.INVISIBLE);

                  }
              });

                     }
      });

    }

and you need to create to file too 1 the adapter class for conect listview to list and 2 the layout we need to use in listview

并且您还需要创建文件 1 用于连接列表视图的适配器类要列出 2 我们需要在列表视图中使用的布局

1 adapter

1个适配器

回答by aioobe

I'd suggest you use Google Gson, the JSON.orglibrary, or some other Json library for Java.

我建议您使用Google GsonJSON.org库或其他一些用于 Java 的 Json 库。

Further reading:

进一步阅读