Android:POST请求,显示特定文本

时间:2017-03-14 16:02:58

标签: java android json

好的,我对POST和GET请求等概念很陌生。所以我道歉如果这是一个愚蠢的问题。

我在这个TvrdjavaFragment.java中有这个异步任务,它从JSON对象获取并显示一切作为注释(toast)。 例如,我只需要 Temperatura 并将其显示为注释,而不是所有内容。 我的问题是如何从JSON对象中获取特定内容

这是我的TvrdjavaFragment.java文件:

public class TvrdjavaFragment extends Fragment {

    Button btnIdinaperiod;
    TextView pokaziServer;
    String rezultat = "";
    String strURL = "http://MYLINK";

    public TvrdjavaFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_tvrdjava, container, false);
        // Inflate the layout for this fragment

        pokaziServer = (TextView) view.findViewById(R.id.testServer);
        //int i = Integer.parseInt(pokaziServer.getText().toString());

        //Log.d("TAG", "TestLogIvan");
        new NabaviServer().execute();

        btnIdinaperiod = (Button) view.findViewById(R.id.buttonIdinaperiod);

        btnIdinaperiod.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PeriodFragment periodFragment = new PeriodFragment();
                FragmentTransaction periodFragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                periodFragmentTransaction.replace(R.id.frame, periodFragment);
                periodFragmentTransaction.addToBackStack(null); //Kada pretisne BACK, vrati se nazad
                periodFragmentTransaction.commit();
            }
        });

        return view;
    }

    public class NabaviServer extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            //super.onPostExecute(s);

            Toast.makeText(getActivity(), "Izlazak je: " + rezultat,Toast.LENGTH_LONG).show();
            Log.i("IVANTAG", rezultat);
        }

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

            try{
                URL url = new URL(strURL);
                HttpURLConnection con = (HttpURLConnection)url.openConnection();
                con.setRequestMethod("POST");
                con.connect();

                BufferedReader bf = new BufferedReader(new InputStreamReader(con.getInputStream())); //??s

                String value = bf.readLine();
                System.out.println("test " + value);
                rezultat = value;


            }
            catch(Exception e)
            {
                System.out.println(e);
            }

            return null;
        }
    }

}

这就是我的JSON对象的样子:

[
  {
    "id": 1,
    "vPritisak": "1",
    "vVazduha": "0",
    "nVisina": "0",
    "temperatura": "0",
    "metan": "0",
    "uDioksid": "1",
    "lokacija": "Kicevo",
    "created_at": null,
    "updated_at": null
  },
  {
    "id": 2,
    "vPritisak": "0",
    "vVazduha": "2",
    "nVisina": "0",
    "temperatura": "0",
    "metan": "0",
    "uDioksid": "0",
    "lokacija": "Cair",
    "created_at": null,
    "updated_at": null
  },
etc...

修改: 当我尝试添加JSONObject jObj = new JSONObject(s);时,我只是得到错误&#34;未处理的异常:org.json.JSONException&#34; 。 当我尝试添加Try-Catch(就像它建议的那样)时,应用程序崩溃了:

       @Override
    protected void onPostExecute(String s) {
        //super.onPostExecute(s);

        try {
            JSONObject jObj = new JSONObject(s);
            String temperatura = jObj.getString("temperatura");//get ur temperatura here

            //try to toast it out,to see the value
            Toast.makeText(getActivity(), "Izlazak je: " + temperatura,Toast.LENGTH_LONG).show();

        } catch (JSONException e) {
            e.printStackTrace();
        }


        Toast.makeText(getActivity(), "Izlazak je: " + rezultat,Toast.LENGTH_LONG).show();
        Log.i("IVANTAG", rezultat);
    }

4 个答案:

答案 0 :(得分:1)

您的回复是JSONArray

JSONArray array_data = new JSONArray(value);
JSONObject object_data = array_data.getJSONObject(0); // 0, 1, 2 index of array

您可以从对象获取任何数据

object_data.getString("temperatura");

答案 1 :(得分:0)

您需要解析服务器响应,这是一个JSON格式的字符串,您可以这样做(在onPostExecute方法中):

try {
    JSONArray serverResponseArray = new JSONArray(yourServerResponseString); 
    // looping through all items of array
    for (int i = 0; i < serverResponseArray.length(); i++) {
        JSONObject item = serverResponseArray.getJSONObject(i);
        String temperatura = item.getString("temperatura");
        // Now you can do what you want with temperatura (Toast, log...)
        ...
    }
}
catch(JSONException e) {
    // Do something of input string is in fact not JSON well-formed or if specified key does not exist in JSON
}

答案 2 :(得分:0)

onPostExecute处,您需要解析Json对象并将其存储为值

@Override
protected void onPostExecute(String s) {
     //super.onPostExecute(s);
 try{
     JSONObject jObj = new JSONObject(s);
     String temperatura = jObj.getString("temperatura");//get ur temperatura here

      //if you want,you can get other value as well,example
      String nVisina = jObj.getString("nVisina"); //etc.....

      //do whatever you like here to process your String value

    //try to toast it out,to see the value
    Toast.makeText(getActivity(), "Izlazak je: " + temperatura,Toast.LENGTH_LONG).show();

 }catch(JSONException e){
   //Json error,do something here,normally will handle like this
    e.printStackTrace();
    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();

  }
}

您的应用因为您在Toast区域外尝试try/catch而崩溃的原因..

 Toast.makeText(getActivity(), "Izlazak je: " + rezultat,Toast.LENGTH_LONG).show();
    Log.i("IVANTAG", rezultat);
   //u make this line outside the `try` block

答案 3 :(得分:0)

试试这个:

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";
//JSON from String to Object
User user = mapper.readValue(jsonInString, User.class);

除了使jsonInString =你的回复。 关于杰克逊的更多信息:https://github.com/FasterXML/jackson-core

这是依赖关系,虽然'我不确定这是否足够,但你可以查看他们的github,看看它是如何工作的:

compile( [group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.4.1'], [group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.4.1'], [group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.4.1'] )