java - 字符串到 JSON (android)

标签 java android eclipse json

我陷入了一个非常棘手的境地。所以,我要做的是从我的本地主机数据库中获取 JSON 对象。当我在浏览器中输入 url ( http://localhost./embrace/test_get.php?nr=1) 时,它回显:

{
    "nr": "1",
    "pav": "MANTAS"
}

我已经检查过这个 JSON,它似乎是有效的。此外,我几乎整天都在 StackOverflow 中搜索解决方案,但没有一个有效。所以,这是我的代码:

  public class MainScreenActivity extends Activity implements OnClickListener             {

    EditText laukas;
    Button mygtukas;
    InputStream is = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);
        laukas = (EditText)findViewById(R.id.editText1);
        mygtukas = (Button)findViewById(R.id.button1);
        mygtukas.setOnClickListener(this);

    }

    @Override
    public void onClick(View v){

        String lokacija = "http://localhost./embrace/test_get.php?nr=1"; /* dont be mad about localhost, i have working adress which i've tested via pc and android browser, it's just because stackoverflow policy */

        URL url = null;
        try {
            url = new URL(lokacija);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            Log.d("KLAIDA",e.toString());
        }

        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.d("KLAIDA",e.toString());
            }

        try {
            conn.setRequestMethod("GET");
        } catch (ProtocolException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }

        conn.setDoInput(true);

        try {
            conn.connect();
        } catch (IOException e) {
                // TODO Auto-generated catch block
            Log.d("KLAIDA",e.toString());
            }

        try {
            is = conn.getInputStream();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String contentAsString = null;   
        try {
            contentAsString = readIt(is, 500);
            //is.close();
            if(contentAsString != null){
            //textView.setText(contentAsString);
            } //else textView.setText("nuliukas");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            Log.d("KLAIDA",e.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.d("KLAIDA",e.toString());
        }

        conn.disconnect();
            int sum = 0;
        for(int i =0;i<contentAsString.length();i++){
            if(contentAsString.charAt(i)==('"'))
                sum++;
        }


        try {
            JSONObject b = new JSONObject();
            b.getJSONObject(contentAsString); // CRASH HERE
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Toast.makeText(MainScreenActivity.this,sum+"",Toast.LENGTH_SHORT).show();

          }

        public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
            Reader reader = null;
            reader = new InputStreamReader(stream, "UTF-8");        
            char[] buffer = new char[len];
            reader.read(buffer);
            return new String(buffer);
        }
}

我的 test_get.php 类

<?php
$con = mysqli_connect("localhost","root","","embrace_db");
//if(mysqli_connect_errno($con))
    //echo "Failed to connect to MySQL: ";
    //else echo "Connected successfully";
$output = array();
$nr = $_GET['nr'];
$q = mysqli_query($con,"SELECT * FROM duomenys WHERE nr = '$nr' ");
while ($e=mysqli_fetch_assoc($q))
    $output = $e;

echo (json_encode($output));

mysqli_close($con);
?>

LogCat 输出

07-29 21:52:10.399: W/System.err(12985): org.json.JSONException: No value for {"nr":"1","pav":"MANTAS"}??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
07-29 21:52:10.409: W/System.err(12985):    at org.json.JSONObject.get(JSONObject.java:354)
07-29 21:52:10.409: W/System.err(12985):    at org.json.JSONObject.getJSONObject(JSONObject.java:569)
07-29 21:52:10.409: W/System.err(12985):    at com.damkell.wamptutorial.MainScreenActivity.onClick(MainScreenActivity.java:123)
07-29 21:52:10.409: W/System.err(12985):    at android.view.View.performClick(View.java:2485)
07-29 21:52:10.409: W/System.err(12985):    at android.view.View$PerformClick.run(View.java:9080)
07-29 21:52:10.409: W/System.err(12985):    at android.os.Handler.handleCallback(Handler.java:587)
07-29 21:52:10.409: W/System.err(12985):    at android.os.Handler.dispatchMessage(Handler.java:92)
07-29 21:52:10.409: W/System.err(12985):    at android.os.Looper.loop(Looper.java:123)
07-29 21:52:10.409: W/System.err(12985):    at android.app.ActivityThread.main(ActivityThread.java:3729)
07-29 21:52:10.409: W/System.err(12985):    at java.lang.reflect.Method.invokeNative(Native Method)
07-29 21:52:10.409: W/System.err(12985):    at java.lang.reflect.Method.invoke(Method.java:507)
07-29 21:52:10.409: W/System.err(12985):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874)
07-29 21:52:10.409: W/System.err(12985):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:632)
07-29 21:52:10.409: W/System.err(12985):    at dalvik.system.NativeStart.main(Native Method)

P.S 这就是我已经尝试过的: 要更正接收到的字符串结尾,请删除 /n 标记; 使用略有不同的方法 http://www.helloandroid.com/tutorials/connecting-mysql-database但随后 LogCat 在字符 0 处抛出输入结束,我也尝试记录我的输出(从 HTTP 接收的字符串,它与来自浏览器的相同(漂亮的 JSON 字符串)); 因此,如您所见,我已经尝试了很多,但似乎每种可能的解决方案都存在问题。提前致谢:)

已解决!!! 特别感谢 jteezy14 ! 正如他所说,这不是确切的问题,但实际上他引导我走上了正确的道路。 应该是:

JSONObject b=null;


    try {
                b = new JSONObject(naujas);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                Log.e("JSONKE",e1.toString());
            }

代替:

JSONObject b = new JSONObject();
    try{
        b.getJSONObject(naujas);
    } catch (JSONException e1) {
      Log.e("JSONKE",e1.toString());
    }

另外,感谢 Kimmax 格式化我的答案并使其更易于理解;)

最佳答案

发生这种情况的原因是因为您在 readIt() 函数中创建了一个长度为 500 个字符的字符串。您的 JSON 表达式 {"nr":"1","pav":"MANTAS"} 是有效的,但尾随字符使其无效 JSON。这就是为什么在 logcat 中您在 JSON 表达式后得到这么多问号。

为了解决这个问题,您需要从 JSON 字符串中删除多余的字符。

编辑(阅读您的评论后):

我的回答的第一部分是必要的,但您还必须以不同的方式使用 JSONObject。查看 Android JSONObject 的文档

http://developer.android.com/reference/org/json/JSONObject.html#getJSONObject(java.lang.String)

您正在使用的函数期望输入值是 JSON 对象的键(这就是为什么您收到错误提示没有值,因为您指定的键不存在) .您需要创建传递字符串的对象,然后获取值:

JSONObject b = new JSONObject(contentAsString)
JSONObject valAtNr = b.getJSONObject("nr"); //value at nr
JSONObject valAtPav = b.getJSONObject("pav"); //value at pav

关于java - 字符串到 JSON (android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25002558/

相关文章:

java - 在不使用拆分或循环的情况下使用 IndexOf 和子字符串拆分字符串

android - Android 上的 Admob : banner space not reserved before loading

eclipse :c/c++构建/构建器设置页面已禁用(灰色),无法更改设置

java - 为什么当我更改最大堆大小时 Eclipse 打不开?

Java 如何将可变参数传递给另一个函数,如 Paths.get()

java - 如何在按下窗口关闭按钮时最小化 jFrame?

java - Remoteclass 类类型缺失

java - DecorContext 转换 Activity

java - 将 Google+ 个人资料图片从 Uri 获取到 Android 上的位图

eclipse - 为什么我们无法从主网站下载 SWT 的 Javadocs jar 文件