在Java中解析服务器响应并将值保存到Java变量

时间:2018-01-09 14:57:22

标签: java android arrays json

我是第一次开发一个Android应用程序,并且有一些关于用Java解析数据的问题,这些数据是通过HTTP解析从服务器提供的。现在,我能够测试一个简单的连接,回复“数据匹配”并成功读取。这意味着我的服务器端代码是正确的,以及我如何获取信息。

我的下一步是将我的PHP服务器响应转为JSON并发送给Java。但我不确定如何让Java读取我将要发送的JSON数组,并将这些部分保存到Java中的可访问变量中。

我已经回顾了以下两个stackoverflow问题,但我仍然不确定如何在现有代码中实现该建议。

How to parse a JSON and turn its values into an Array?

How to get data as an json array from a server and convert it in to java array to use in android application

我的代码:

HttpParse:

package [domain_package].lexaapp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by rachel.dimouro on 12/6/2017.
*/

public class HttpParse {

  String FinalHttpData = "";
  String Result ;
  BufferedWriter bufferedWriter ;
  OutputStream outputStream ;
  BufferedReader bufferedReader ;
  StringBuilder stringBuilder = new StringBuilder();
  URL url;

  public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {

    try {
        url = new URL(HttpUrlHolder);

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setReadTimeout(14000);

        httpURLConnection.setConnectTimeout(14000);

        httpURLConnection.setRequestMethod("POST");

        httpURLConnection.setDoInput(true);

        httpURLConnection.setDoOutput(true);

        outputStream = httpURLConnection.getOutputStream();

        bufferedWriter = new BufferedWriter(

                new OutputStreamWriter(outputStream, "UTF-8"));

        bufferedWriter.write(FinalDataParse(Data));

        bufferedWriter.flush();

        bufferedWriter.close();

        outputStream.close();

        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

            bufferedReader = new BufferedReader(
                    new InputStreamReader(
                            httpURLConnection.getInputStream()
                    )
            );
            FinalHttpData = bufferedReader.readLine();
        }
        else {
            FinalHttpData = "Something Went Wrong";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return FinalHttpData;
  }

  public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {

    for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){

        stringBuilder.append("&");

        stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));

        stringBuilder.append("=");

        stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));

    }

    Result = stringBuilder.toString();

    return Result ;
  }
}

Java函数作用于数据:

    public void SGSearchFunction(final String SearchInput){

    class SGSearchClass extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = ProgressDialog.show(DashboardActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog.dismiss();

            // is this where I should put the code for the array, or does it go in the HttpParse section?
            if(httpResponseMsg.equalsIgnoreCase("Data Matched")){ 

                finish();

                Intent intent = new Intent(DashboardActivity.this, SGInfoActivity.class);

                intent.putExtra(SearchValue, SearchInput);

                startActivity(intent);


            } else {

                Toast.makeText(DashboardActivity.this,httpResponseMsg,Toast.LENGTH_LONG).show();
            }

        }

        @Override
        protected String doInBackground(String... params) {

            hashMap.put("SearchInput",params[0]);

            finalResultSearch = httpParse.postRequest(hashMap, HttpURL);

            return finalResultSearch;
        }
    }

    SGSearchClass sgSearchClass = new SGSearchClass();

    sgSearchClass.execute(SearchInput);
}

感谢所有帮助。

谢谢!

0 个答案:

没有答案