当前位置: 首页 > 面试题库 >

解析JSON以配置Android应用程序

隆宏爽
2023-03-14
问题内容

在我的Android应用程序中,我必须使用服务器上的JSON才能在应用程序中进行特定调整。我试图达到的目的是读取此json并将所有值存储到局部变量中以在应用程序内执行操作。

来自服务器的JSON:

[

    {
        "sett": " ",
        "glHdr": {
            "sm": [ ],
            "scleHPad": false,
            "st": "sbsm"
        },
        "colrBG": [
            23,
            105,
            184,
            100
        ],
        "colrTB": [
            0,
            0,
            0,
            0
        ],
        "colrTR": [
            255,
            255,
            255,
            100
        ],
        "glFtr": {
            "icoSz": "icoSzN",
            "sm": [ ],
            "scleHPad": false,
            "gvNR": 3,
            "gvHIT": false,
            "gvNC": 3,
            "st": "igsm"
        },
        "statBr": true
    },
    {
        "sm": [
            {
                "tbico": "b43-jeep.png",
                "t": "Welcome!",
                "w": "http://google.com/start",
                "st": "w",
                "wTBL": "wTBLN"
            },
            {
                "t": "Content screen title",
                "f": "Eltec%20Spec%20sheet%20Gim%20RD30W.pdf",
                "st": "f"
            },
            {
                "tbico": "109-chicken.png",
                "t": "Sub menu",
                "sm": [
                    {
                        "t": "Screen 1",
                        "st": "f"
                    },
                    {
                        "t": "Screen 2",
                        "w": "Http://google.com",
                        "st": "w",
                        "wTBL": "wTBLT"
                    }
                ],
                "st": "sm"
            },
            {
                "st": "f"
            }
        ],
        "st": "tbm"
    }

]

为了进行解析,我创建了Parse JSON类,并尝试提出在我的应用中读取和存储此JSON值的方法。

执行此操作的功能:

public void doScanAppConfigJson(){

private static final String = TAG_TITLE;
private static final String = TAG_WEB_ADDRESS;
private static final String = TAG_SCREEN_TYPE;
private static final String = TAG_FILENAME;


        JSONArray appConfig = null;

        // Function for looping json object via ParseJson class.
        //Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        //Getting json strings from url
        JSONObject jsonObject = jParser.getJSONFromUrl(url);

    try{
        //Getting array of settings
        appConfig = jsonObject.getJSONArray(ConfigConstants.TABLE_VIEW_SUB_MENU_CONFIG);
        //loop throw all the objects under -sm[]
        for (int i = 0; i < appConfig.length(); i++){

            JSONObject sm = appConfig.getJSONObject(i);

            //Now store each of this json in local constant var.

            String tabTitle = sm.getString(TAG_TITLE);

            String webAddress = sm.getString(TAG_WEB_ADDRESS);

            String screenType = sm.getString(TAG_SCREEN_TYPE);

            String fileName = sm.getString(TAG_FILENAME);

        }

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

    }

    }

getJSONFromUrl方法:

public JSONObject getJSONFromUrl(String url) {

        //Global authentication for link username and password.
        Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication(){

            return new PasswordAuthentication("username", "password".toCharArray());   
            }

        });

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

我正在收到错误:settingsjava.lang.NullPointException在此但我已经定义了vars,请有人告诉我我如何解析JSON。我在正确的道路上实现答案吗?我的问题?


问题答案:

当前的json字符串格式为:

[  //<<<< JSONArray

    {   //<<<< JSONObject
       // other items here...
    }

]

此Json字符串内容JSONArray作为root元素而不是JSONObject。您将需要先将其转换为JSONArray,然后从中提取JSONObject:

JSONArray jsonObject = jParser.getJSONFromUrl(url);

也将getJSONFromUrl方法返回类型更改为JSONArray



 类似资料:
  • 问题内容: 我需要在Java Android Appl中解析json字符串的帮助。 JSON文件的文本: 如何获取值:location_id,名称,纬度,经度。谢谢,米哈尔。 问题答案: 使用手动解析,您可以这样实现: 在您的案例中,请注意您的外部元素数据是JSONObject类型,然后您有了一个JSONArray 我的json文件: 请注意,我的从[开始,这意味着一个数组,但您的是从{开始,然后

  • 问题内容: 现在完成XML SAX解析之后,我将在应用程序中进行JSON解析。我在这里为您提供杰森 现在,我提到了一个Json解析的示例,在该示例中,他们创建了一个jString对象,我对此特定行有疑问,如下所示: 任何人都可以让我澄清一下。完整示例的链接如下: http://www.androidcompetencycenter.com/2009/10/json-parsing-in- andr

  • 您好,我有这个代码,我想将此数据解析为对象,现在我得到了一个 anyType 的字符串 我想分别得到描述对象纬度对象和经度对象

  • Name: 名字. 可以在工具栏运行应用程序配置的下拉列表中看到。 General: 在这里配置安装、启动、部署应用程序选项 Module: 列表中列出了当前项目中的所有模块,我们可以指定相应的模块来运行. Installation Options: 安装选项 1.Deploy:下拉列表中列出了应用程序运行时的部署模式 有三个选项: Default APK: 部署默认的APK, 运行时会先打包安装

  • 我有这个JS代码: 我的JSON看起来像:{“日期”:“2017-03-27”,“顺序”:“61”,“数据”:[{“国家标签”:“澳大利亚”,“货币标签”:“多拉尔”,“单位”:“1”,“代码”:“澳元”,“汇率”:“18.946”},{“国家标签”:“巴西”,“货币标签”:“真实”,“单位”:“1”,“代码”:“BRL”,“汇率”:“7.951”},{“国家标签”Bulharsko,“货币标签”

  • 我正在使用一个JSON解析器从我的JSON文件中读取数据并将其显示在我的应用程序中,我最初使用这段代码创建数组,它工作良好,但现在我已经将它粘贴到一个新的应用程序中,使它从JSON获取数据并将其放到一个不工作的文本字段中。我会在下面贴出代码和错误日志。 d/test:http://curtisboylan.me/mygeek/mygeekprofile.php?user=1 e/egl_emula