JSON - single file to use with android app

六眼飞鱼酱① 提交于 2019-12-24 03:07:43

问题


I got this app that requires four places on screen to be up-to-date (title, address, date and image source).

So, I thought that maybe I could just makeup four different JSON files that app will read and if I would like to change what app is showing I would just change those JSON files that I'd have on my server.

Maybe something like this (file.json):

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

and in Android app source of course there would be JSONParser that will get informations from "http://myserver.com/file.json". What do You think - would be that good enough or is there any better (and easier) solution? I tried to get to know Google Endpoints, but it's really cumbersome.

edit1: I got to this point where I use JSONParser custom class from here: How to parse JSON in Android In debug mode I found values from file.json to be downloaded so I have to read it somehow now - it prints "Got the address: " but without value:

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: my XML suddenly stopped working (it validates and makes hierarchy tree well, but not every time):

{
   "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 validators says that it's okay or SyntaxError: unexpected token.

This is my JSONParser.java class:

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;

}

}


回答1:


Yes, obtaining data from your server as a JSON file seems to be the best and most lighweight way of solving this (although you provided little data on what the data should actually mean).

I would suggest using org.json library, as it will allow you to do something like this, cutting time on the parsing:

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 */
}



回答2:


Well, I have a very nice idea, i would suggest using the Gson library.

available from here, with perfect tutorial here

With Gson library you can simply convert JSON To/From java object ! Try to create class with name: 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;
}


}

Then try to use the Gson library, it will get the json file than using the .fromJSON function it will return an instance of app.java

I hope it will help you, best regards.



来源:https://stackoverflow.com/questions/27468834/json-single-file-to-use-with-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!