1

I use below code to produce JSON string and parse it in php. I create an instace of this class and call setData method

 //#PART1
    String s = "{\"Category\":";
    List<CategoryModel> pmo = new ArrayList<CategoryModel>();
    pmo = CategoryModule.getAllRecords(c);
    s += new JSONSerializer().serialize(pmo);
    s += ",\"Data\":";

    //#PART2
    List<DataModel> amo = new ArrayList<DataModel>();
    amo = DataModule.getAllRecords(c);
    s += new JSONSerializer().serialize(amo);

    s += "}";

I decode the result by below code

$categories =  json_decode($data)->{'Category'};
$datas = json_decode($data)->{'Data'};
$username = "kkk";
foreach($categories as $category){
   $id =  $category->{'id'};
   $name = $category->{'name'};
   $sql = "INSERT INTO category (id,name,username) VALUES ('$id','$name','$username')";

   $link->query($sql);
}


foreach($datas as $data){
   $id =  $data->{'id'};
   $text = $data->{'text'};
   $date = $data->{'date'};

   $sql = "INSERT INTO data (id,text,date,username) VALUES ('$id','$name','$date','$username')";

   $link->query($sql);
}

When I just use #PART1 to produce json string in the php code the decoding occurs in success. But when I add #PART2 to JSON string no one of them decodes successfully. I guess the problem can be from java code. Please guide me

JSON result is http://aiga.ir/webservice/datastore/a.txt

I use this code for sending data

package ir.aiga.apps.network;


public class WebServiceComm  extends AsyncTask<String, Void, Void> {

    // Required initialization


    private String Content;
    private String Error = null;
    private ProgressDialog Dialog;
    private String data ="";
    private boolean visible=true;









    private InterFace doInPreExecute=new InterFace() {

        @Override
        public void doSomething() {
            // TODO Auto-generated method stub

        }

        @Override
        public void getResult(String output) {
            // TODO Auto-generated method stub

        }

        @Override
        public void getJSONArray(JSONArray array) {
            // TODO Auto-generated method stub

        }




    };
    private InterFace doInPostExecute=new InterFace() {

        @Override
        public void doSomething() {
            // TODO Auto-generated method stub

        }



        @Override
        public void getResult(String output) {
            // TODO Auto-generated method stub

        }



        @Override
        public void getJSONArray(JSONArray array) {
            // TODO Auto-generated method stub

        }
    };



    public WebServiceComm(Context context,String title,String text){

        try {
            data +="&" + URLEncoder.encode("data", "UTF-8") + "=";
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Dialog=new ProgressDialog(context,ProgressDialog.STYLE_SPINNER);

        Dialog.setTitle(title);
        Dialog.setMessage(text);
    }

    public WebServiceComm(){
        try {
            data +="&" + URLEncoder.encode("data", "UTF-8") + "=";
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public void setData(String data){
        this.data+=data;
    }

        protected void onPreExecute() {
        // NOTE: You can call UI Element here.
        if(visible)
        Dialog.show();

    }

    // 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();
                ex.printStackTrace();
            }
            finally
            {
                try
                {

                    reader.close();
                }

                catch(Exception ex) {
                    ex.printStackTrace();
                }
            }

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

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


        if (Error != null) {



        } else {

            // Show Response Json On Screen (activity)


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

            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("Android");





                    doInPostExecute.getJSONArray(jsonMainNode);
                    doInPostExecute.doSomething();
                    if(visible)
                    Dialog.dismiss();







             } catch (Exception e) {

                 e.printStackTrace();
             }


         }
    }



    /**
     * @return the doInPreExecute
     */
    public InterFace getDoInPreExecute() {
        return doInPreExecute;
    }



    /**
     * @param doInPreExecute the doInPreExecute to set
     */
    public void setDoInPreExecute(InterFace doInPreExecute) {
        this.doInPreExecute = doInPreExecute;
    }



    /**
     * @return the doInPostExecute
     */
    public InterFace getDoInPostExecute() {
        return doInPostExecute;
    }



    /**
     * @param doInPostExecute the doInPostExecute to set
     */
    public void setDoInPostExecute(InterFace doInPostExecute) {
        this.doInPostExecute = doInPostExecute;
    }


    /**
     * @return the visible
     */
    public boolean isVisible() {
        return visible;
    }


    /**
     * @param visible the visible to set
     */
    public void setVisible(boolean visible) {
        this.visible = visible;
    }

}
Ali
  • 508
  • 1
  • 5
  • 16

2 Answers2

0

It's very bad to manually build JSON manually.

Using a JSON Mapper library

public class MyCustomModel {
    public List<CategoryModel> Category;
    public List<DataModel> Data;
    public class CategoryModel{
        //code here
    }
    public class DataModel{
        //code here
    }   
}

Then use it GSON to serialize that object into JSON

MyCustomModel customModel = new MyCustomModel();
//populate object
//......
Gson gson = new Gson();  
String json = gson.toJson(customModel); 

Using standard library

JSONArray categoryArr = new JSONArray();
List<CategoryModel> categories = CategoryModule.getAllRecords(c);
for (CategoryModel category : categories) {
    JSONObject categoryObj = new JSONObject();
    categoryObj.put("class", category.getClass());
    categoryObj.put("id", category.getId());
    categoryObj.put("name", category.getName());
    categoryArr.put(categoryObj);
}

Then do the same with the other list then combine both array

JSONObject jObject = new JSONObject();
jObject.put("Category", categoryArr);
jObject.put("Data", dataArr);
meda
  • 45,103
  • 14
  • 92
  • 122
  • Thank you, But the source json string is correct when I receive over http by post it doesn't reveive completly and gives json parse error – Ali Jun 30 '15 at 22:00
  • Your code is better way to make json, I will use it! thank you very much – Ali Jun 30 '15 at 22:32
0

please try to use this code for sending and receiving JSON with utf-8 encoding:

try {
        URL url = new URL("your url");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(
                conn.getOutputStream(), "UTF-8");
        String request = "your json";
        writer.write(request);
        writer.flush();
        System.out.println("Code:" + conn.getResponseCode());
        System.out.println("mess:" + conn.getResponseMessage());

        String response = "";
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            response += line;
        }

        System.out.println(new String(response.getBytes(), "UTF8"));
        writer.close();
        reader.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
Safwan Hijazi
  • 2,089
  • 2
  • 17
  • 29