JSON - 与Android应用程序一起使用的单个文件

时间:2014-12-14 11:26:26

标签: android json android-json

我有这个应用程序需要屏幕上的四个位置是最新的(标题,地址,日期和图像源​​)。

所以,我想也许我可以只构建应用程序将读取的四个不同的JSON文件,如果我想更改应用程序显示的内容,我只会更改我在服务器上拥有的那些JSON文件。

也许像这样(file.json):

{"app": {
  "title": "Screen no. 1",
  "address": "Sesame Street",
  "date": "01-01-2014",
  "image": "http://myserver.com/image.jpg"
}}

并且在Android应用程序源中当然会有JSONParser从“http://myserver.com/file.json”获取信息。你怎么想 - 会是那么好还是有更好(更容易)的解决方案?我试图了解谷歌终端,但它真的很麻烦。

edit1:我到了这里,我从这里使用JSONParser自定义类:How to parse JSON in Android 在调试模式下,我发现要下载file.json中的值,所以我现在必须以某种方式读取它 - 它打印“获取地址:”但没有值:

Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {
            try {
                Log.i("ABCDE", "Start Thread");
                //JSON
                JSONParser jparser = new JSONParser();
                JSONObject data = jparser.getJSONFromUrl("http://myserv.com/file.json");                
                Log.i("AbCDE", "Afer getting JSON");
                //JSONObject data = new JSONObject(myDataJson); 

                String address = "";

                try {
                    address = data.getString("address");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                Log.i("ABCDE", "Got the address: " + address);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

edit2:我的XML突然停止工作(它验证并使层次结构树很好,但不是每次都有):

{
   "party1": {
      "title": "Screen no. 1",
      "address": "Sesame Street",
      "date": "01-01-2014",
      "image": "http://myserver.com/image.jpg",
      "destination": "somewhere"
   },
   "party2": {
      "title": "Screen no. 2",
      "address": "Oak Street",
      "date": "01-01-2014",
      "image": "http://myserver.com/image.jpg",
      "destination": "somewhere"
   },
   "party3": {
      "title": "Screen no. 1",
      "address": "Sesame Street",
      "date": "01-01-2014",
      "image": "http://myserver.com/image.jpg",
      "destination": "somewhere"
   },
   "party4": {
      "title": "Screen no. 1",
      "address": "Sesame Street",
      "date": "01-01-2014",
      "image": "http://myserver.com/image.jpg",
      "destination": "somewhere"
   }
}

JSON验证器说它没问题或者是SyntaxError:意外令牌。

这是我的JSONParser.java类:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {}

public JSONObject getJSONFromUrl(String url) {

    // 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;

}

}

2 个答案:

答案 0 :(得分:2)

是的,从您的服务器获取数据作为JSON文件似乎是解决此问题的最佳和最轻量级的方法(尽管您提供的数据实际上并不重要)。

我建议使用org.json库,因为它可以让你做这样的事情,缩短解析时间:

String myDataJson = ... /* Obtain the data here */
long lastChangeTimestamp = ... /* Obtain the last saved timestamp, probably from SharedPrefs */

JSONObject data = new JSOBObject(myDataJson);

long newTimestamp = data.getLong("ts");
if(newTimestamp > lastChangeTimestamp){ 

String title = data.getString("title");
String address = data.getString("address");
String date = data.getString("date");
String image = data.getString("image");

/* Do somtehing with the newly obtained data and save the new timestamp to SharedPrefs */
}

答案 1 :(得分:1)

好吧,我有一个非常好主意,我建议使用Gson库。

可从here获得,完美教程here

使用Gson库,您只需将JSON转换为/从java对象! 尝试创建名称为app的类:app: 的 app.java:

public class app {
public String title;
public String address;
public String date;
public String image;

public app() {
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}


}

然后尝试使用Gson库,它将获取json文件,而不是使用 .fromJSON 函数,它将返回 app.java

的实例

我希望它会对你有所帮助,最好的问候。