-1

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:

    {
   "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:

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 ???

  • Please post what error you are getting, including any relevant LogCat output. – Ken Y-N May 11 '16 at 00:40
  • Has no log error, the problem is that he can not get the data that is in the custom fields like "name", "pass" – Tiago Góes May 11 '16 at 00:47
  • Well, in that case, you are not retrieving the `custom_field` child node before trying to get the `name`. Note that `optString`, `getString` and friends only search the current level, not the whole subtree. Stepping through the code with a debugger would have revealed this, so please try that out. – Ken Y-N May 11 '16 at 02:46

2 Answers2

1

At the moment I'm developing an app that communicates with a server via REST services almost all the time. 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. Then I can get the response as a String (in fact, it's really a stringified 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. 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:

An annotation that indicates this member should be serialized to JSON with the provided name value as its field name.

So, the string passed to SerializedName should be the key of the item in your JSON response. Then, back in onPostExecute(), you can parse the JSON string like this:

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 :).

Nadia Castelli
  • 147
  • 2
  • 11
0

Your json response is pretty complex to access custom_fields items. Instead of array you can put all those items of custom_fields as key-value pair eg."name":"name_value", however below code shows how to read those values.

        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

Bharatesh
  • 8,943
  • 3
  • 38
  • 67