【问题标题】:Android: POST request, show specific textAndroid:POST请求,显示特定文本
【发布时间】:2017-03-14 16:02:58
【问题描述】:

好的,我对 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); 时,我只收到错误“Unhandled exception: org.json.JSONException”。 当我尝试添加 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);
    }

【问题讨论】:

  • 寻找 GSON lib 它是你应该使用的。
  • 需要解析Json..获取值

标签: java android json


【解决方案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");

【讨论】:

  • 首先我得到一个错误Unhandled exception: org.json.JSONException,然后我添加 Try - Catch ,喜欢它的建议,仍然没有,看:imgur.com/a/q1EQ6跨度>
  • @IkePr,把你的代码写在 try catch 块try { .... .... } catch (JSONException e) { }
【解决方案2】:

试试这个:

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'] )

【讨论】:

    【解决方案3】:

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

    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
    }
    

    【讨论】:

    • 我在新的 JSONObject(s) 处收到此错误 - 未处理的异常:org.json.JSONException。当我添加 try - catch 时,应用程序会在我启动时崩溃。
    【解决方案4】:

    在您的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();
    
      }
    }
    

    您的应用程序崩溃的原因是因为您尝试在try/catch 块之外使用Toast..

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

    【讨论】:

    • 我在新的 JSONObject(s) 处收到此错误 - 未处理的异常:org.json.JSONException。当我添加 try - catch 时,应用程序会在我启动时崩溃。
    • 我更新了我的答案,尝试在你的onPostExecute部分运行这个,应该没问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    相关资源
    最近更新 更多