如何从特殊格式字符串中获取值?

时间:2013-02-08 09:21:47

标签: java android json string

我从web api获得一个字符串,如{“time”:“08:05”,“code”:“CSTM”,“name”:“MUMBAI CST”},此字符串不能转换为JSONObject,因为这个原因我无法从字符串中获取值。如何从字符串中获取值?

1 个答案:

答案 0 :(得分:0)

           link = new URL("The url");
           InputStream in = link.openStream();
          LoadRegistration_Api(in);

            protected void LoadRegistration_Api(InputStream json)   
                                     throws IOException, JSONException {
        // TODO Auto-generated method stub

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                json));
        StringBuilder sb = new StringBuilder();
        String line = reader.readLine();
        while (line != null) {
            sb.append(line);
            line = reader.readLine();
        }
        reader.close();

        JSONObject jobj = new JSONObject(sb.toString());

        if (jobj.has("time")) // handle Se_wesam

        {
            Result = jobj.getString("time");

        }

        if (jobj.has("code")) // handle Se_wesam

        {
            UserId = jobj.getString("code");

        }

    }
}

尝试这个,我认为它会有所帮助