简体   繁体   English

Android从HTML读取JSON

[英]Android Read JSON From HTML

I am using an Android Application to do a request to a Node.js server to complete a function on a MongoDB. 我正在使用Android应用程序向Node.js服务器发出请求,以完成MongoDB上的功能。 I am wondering how can I make the Android Application read the JSON response? 我想知道如何让Android应用程序读取JSON响应? I have tried putting it into a code bracket on the HTML but it makes no difference. 我尝试将其放在HTML上的代码支架中,但没有区别。 I can do this in PHP just fine but for this environment I need to use a HTML file. 我可以用PHP很好地做到这一点,但是对于这种环境,我需要使用HTML文件。 I will attach my HTML and Java code below. 我将在下面附加我的HTML和Java代码。

Response 响应

E/MainActivity: Response from url: <html>
    <script src='/server.js'></script>
    <code>{"Example":[{"success":"1","message":"posted"}]}</code>
    </html>

Java Java的

private class doWeb extends AsyncTask<Void, Void, Void> {

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

            }

            @Override
            protected Void doInBackground(Void... arg0) {
                HttpHandler sh = new HttpHandler();
                String jsonStr = sh.makeServiceCall(url);
                Log.e(TAG, "Response from url: " + jsonStr);
                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);
                        JSONArray contacts = jsonObj.getJSONArray("Example");
                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);
                            if (c.getString("success").equals("1")) {
                            Log.d("complete","post success");
                            }
                            else{
                                Log.d("complete","post fail");
                            }
                        }
                    } catch (final JSONException e) {
                        //error
                    }
                } else {
                    Log.e(TAG, "Couldn't get json from server.");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Couldn't get json from server. Check LogCat for possible errors!",
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
                return null;
            }
            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);

            }
        }

HTML HTML

<html>
<script src="server.js"></script>
<code>
{"Example":[{"success":"1","message":"posted"}]}</code>
</html>

You can use Regex to help you with the JSON extraction. 您可以使用Regex帮助您进行JSON提取。

Then you can simply parse it with Gson Converter. 然后,您可以简单地使用Gson Converter对其进行解析。

Step 1 : Add dependencies in build.gradle 步骤1 :在build.gradle中添加依赖项

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

Step 2 : 第二步

Generate class that will represent your JSON object . 生成代表您的JSON对象的类 You can use jsonschema2pojo 您可以使用jsonschema2pojo

package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Data {

    @SerializedName("Example")
    @Expose
    private List<Example> example = null;

    public List<Example> getExample() {
        return example;
    }

    public void setExample(List<Example> example) {
        this.example = example;
    }

}


package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

    @SerializedName("success")
    @Expose
    private String success;
    @SerializedName("message")
    @Expose
    private String message;

    public String getSuccess() {
        return success;
    }

    public void setSuccess(String success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

Step 3 : You match your pattern and you will get your m.group(1) as a JSON string. 步骤3 :匹配您的模式,您将获得m.group(1)作为JSON字符串。

      String pattern = "<code>\n*(.*)</code>";
      Pattern r = Pattern.compile(pattern);
      Matcher m = r.matcher(jsonStr);
      if (m.find()) {
          String config_settings = m.group(1);
          Gson converter = new Gson();
          ConfigSettings settings = converter.fromJson(config_settings , Data.class);

      }

You can test the code in: https://www.tutorialspoint.com/compile_java_online.php 您可以在以下位置测试代码: https : //www.tutorialspoint.com/compile_java_online.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM