简体   繁体   English

在 Android 上转换 JSON 文件中的对象数组时出错

[英]Error converting a array of objects in JSON file on Android

I have a JSON file that comes from a rest API in wordpress which has a kind custom post with two records of users, I would like to get the data from custom fields users data (id,name,pass,client_type), here is my JSON file:我有一个来自 wordpress 中的 rest API 的 JSON 文件,它有一个带有两条用户记录的自定义帖子,我想从自定义字段用户数据(id、name、pass、client_type)中获取数据,这是我的JSON 文件:

    {
   "status": "ok",
   "count": 2,
   "count_total": 2,
   "pages": 1,
   "posts": [
      {
         "id": 22,
         "type": "userstiago",
         "slug": "rascunho-automatico-2",
         "url": "http://tkdhkd.96.lt/userstiago/rascunho-automatico-2/",
         "status": "publish",
         "title": "Rascunho automático",
         "title_plain": "Rascunho automático",
         "content": "",
         "excerpt": "",
         "date": "2016-05-10 18:00:48",
         "modified": "2016-05-10 18:00:48",
         "categories": [],
         "tags": [],
         "author": {
            "id": 1,
            "slug": "admin",
            "name": "admin",
            "first_name": "Tiago",
            "last_name": "Goes",
            "nickname": "Tiagodread",
            "url": "",
            "description": "Administrador da pagina"
         },
         "comments": [],
         "attachments": [],
         "comment_count": 0,
         "comment_status": "closed",
         "custom_fields": {
            "id": [
               "11111111111111"
            ],
            "name": [
               "Priscila"
            ],
            "pass": [
               "priscila"
            ],
            "client_type": [
               "common"
            ]
         },
         "taxonomy_tipo_cliente": []
      },
      {
         "id": 21,
         "type": "userstiago",
         "slug": "rascunho-automatico",
         "url": "http://tkdhkd.96.lt/userstiago/rascunho-automatico/",
         "status": "publish",
         "title": "Rascunho automático",
         "title_plain": "Rascunho automático",
         "content": "",
         "excerpt": "",
         "date": "2016-05-10 17:41:12",
         "modified": "2016-05-10 17:41:12",
         "categories": [],
         "tags": [],
         "author": {
            "id": 1,
            "slug": "admin",
            "name": "admin",
            "first_name": "Tiago",
            "last_name": "Goes",
            "nickname": "Tiagodread",
            "url": "",
            "description": "Administrador da pagina"
         },
         "comments": [],
         "attachments": [],
         "comment_count": 0,
         "comment_status": "closed",
         "custom_fields": {
            "id": [
               "456589546"
            ],
            "name": [
               "Alfred"
            ],
            "pass": [
               "12345"
            ],
            "client_type": [
               "common"
            ]
         },
         "taxonomy_tipo_cliente": []
      }
   ]
}

and this is the code in Java:这是Java中的代码:

package tiagogoes.wprestandroidreceiver;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button GetServerData = (Button) findViewById(R.id.GetServerData);

        GetServerData.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // WebServer Request URL
                String serverURL = "http://tkdhkd.96.lt/api/get_user_posts/";

                // Use AsyncTask execute Method To Prevent ANR Problem
                new LongOperation().execute(serverURL);
            }
        });

    }


    // Class with extends AsyncTask class

    private class LongOperation extends AsyncTask<String, Void, Void> {

        // Required initialization

        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
        String data = "";
        TextView uiUpdate = (TextView) findViewById(R.id.output);
        TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
        int sizeData = 0;
        EditText txtlogin = (EditText) findViewById(R.id.txtlogin);
        EditText txtsenha = (EditText) findViewById(R.id.txtsenha);
        ArrayList<Usuario> users = new ArrayList<>();
        String loginloc, senhaloc;

        protected void onPreExecute() {
            // NOTE: You can call UI Element here.

            //Start Progress Dialog (Message)
            loginloc = txtlogin.getText().toString();
            senhaloc = txtsenha.getText().toString();

            Dialog.setMessage("Please wait..");
            Dialog.show();

            try {
                // Set Request parameter
                data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + txtlogin.getText();

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

        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {

            /************ Make Post Call To Web Server ***********/
            BufferedReader reader = null;

            // Send data
            try {

                // Defined URL  where to send data
                URL url = new URL(urls[0]);

                // Send POST data request

                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();

                // Get the server response

                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line + "");
                }

                // Append Server Response To Content String
                Content = sb.toString();
            } catch (Exception ex) {
                Error = ex.getMessage();
            } finally {
                try {

                    reader.close();
                } catch (Exception ex) {
                }
            }

            /*****************************************************/
            return null;
        }

        protected void onPostExecute(Void unused) {
            // NOTE: You can call UI Element here.

            // Close progress dialog
            Dialog.dismiss();

            if (Error != null) {

                uiUpdate.setText("Output : " + Error);

            } else {

                // Show Response Json On Screen (activity)
                uiUpdate.setText(Content);

                /****************** Start Parse Response JSON Data *************/

                String OutputData = "";
                JSONObject jsonResponse;

                try {

                    /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                    jsonResponse = new JSONObject(Content);

                    /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
                    /*******  Returns null otherwise.  *******/
                    JSONArray jsonMainNode = jsonResponse.optJSONArray("posts");

                    /*********** Process each JSON Node ************/

                    int lengthJsonArr = jsonMainNode.length();

                    for (int i = 0; i < lengthJsonArr; i++) {
                        /****** Get Object for each JSON node.***********/
                        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                        /******* Fetch node values **********/
                        String id = jsonChildNode.optString("id").toString();
                        String name = jsonChildNode.optString("name").toString();
                        String pass = jsonChildNode.optString("pass").toString();
                        String client_type = jsonChildNode.optString("client_type").toString();


                        Usuario u = new Usuario(id,nome,pass,client_type);

                        users.add(u);


                        for (Usuario us : users) {

                            Log.i("dados WS", us.getNome() + " - " + us.getSenha());

                            if (us.getName().equalsIgnoreCase(loginloc) && us.getPass().equalsIgnoreCase(senhaloc)) {
                                Log.i("Mensagem", "OK");
                            } else {
                                Log.i("Mensagem", "Username or password wrong!");
                            }
                        }


                    }
                    /****************** End Parse Response JSON Data *************/

                    //Show Parsed Output on screen (activity)
                    jsonParsed.setText(OutputData);
                } catch (JSONException e) {

                    e.printStackTrace();
                }


            }
        }

    }

}

it does not bring the data above, someone could help me solve ???上面没有带数据,谁能帮我解决???

At the moment I'm developing an app that communicates with a server via REST services almost all the time.目前我正在开发一个应用程序,它几乎一直通过 REST 服务与服务器进行通信。 Here's what I found to be a way to simplify a lot the communication with the backend:这是我发现的一种简化与后端通信的方法:

  • Use OkHttp , which handles all requests to the server easily.使用OkHttp ,它可以轻松处理对服务器的所有请求。 Then I can get the response as a String (in fact, it's really a stringified JSON).然后我可以将响应作为字符串(实际上,它确实是一个字符串化的 JSON)。
  • Parse this response string with Gson , which prevents me from reading every string from the JSON response and having to parse the data myself.使用Gson解析这个响应字符串,这可以防止我从 JSON 响应中读取每个字符串,而不得不自己解析数据。 For this, I need to have my response previously modelled as a class.为此,我需要将我的响应先前建模为一个类。 For example:例如:

     public class Blog implements Parcelable { @SerializedName("status") private String mStatus; @SerializedName("count") private int mCount; @SerializedName("pages") private int mPages; @SerializedName("posts") private ArrayList <Post> mPosts; // "Post" is another Parcelable model class like this one ... // Implement getters and setters for each variable ... }

SerializedName , according to Gson docs, is:根据 Gson 文档, SerializedName是:

An annotation that indicates this member should be serialized to JSON with the provided name value as its field name.指示此成员应序列化为 JSON 并使用提供的名称值作为其字段名称的注释。

So, the string passed to SerializedName should be the key of the item in your JSON response.因此,传递给 SerializedName 的字符串应该是 JSON 响应中项目的键。 Then, back in onPostExecute(), you can parse the JSON string like this:然后,回到 onPostExecute(),您可以像这样解析 JSON 字符串:

Gson gson = new GsonBuilder().create;
gson.fromJson(responseString, Blog.class);

Hope you find this useful!希望你觉得这个有用! Please ask if there's something I didn't explain well :).请询问是否有我没有很好解释的地方:)。

Your json response is pretty complex to access custom_fields items.您的 json 响应对于访问custom_fields项目非常复杂。 Instead of array you can put all those items of custom_fields as key-value pair eg.您可以将custom_fields所有项目作为键值对,而不是数组,例如。 "name":"name_value" , however below code shows how to read those values. "name":"name_value" ,但是下面的代码显示了如何读取这些值。

        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
        JSONObject fieldsObject = jsonChildNode.getJSONObject("custom_fields");
        JSONArray idArray = fieldsObject.getJSONArray("id");
        String idValue = idArray.getString(0);

        JSONArray nameArray = fieldsObject.getJSONArray("name");
        String nameValue = nameArray.getString(0);

        JSONArray passArray = fieldsObject.getJSONArray("pass");
        String passValue = passArray.getString(0);

        JSONArray clientArray = fieldsObject.getJSONArray("client_type");
        String clientValue = clientArray.getString(0);

visit SO : How to parse JSON in Android 访问 SO:如何在 Android 中解析 JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM