开发者

Parsing JSON into Java from Klout API

I am making a web application that returns the Klout Scores details of Twitter followers. The work flow is as follow :

  1. From Twitter API, get twitter_id of the followers . eg: 48,000 ids of Sachin Tendulkar followers.
  2. get twitter info(screen name,twitter_name,location) for twitter_id received from step 1.
  3. from Klout API , get Klout Scores in JSON format and then parsing JSON into Java.
  4. 开发者_如何转开发
  5. from Klout API ,get Klout Topics in JSON format and then parsing JSON into Java.
  6. Insert Klout and Twitter data into Database.

I am facing problem in parsing JSON into Java. Please suggest solutions. Thanks in advance .

Komal


Take a look at the Setting up a Klout application section of the Direct Media Tips and Tricks book. It explains how to use the dmt-klout library to get the information you are looking for.

If you want to rewrite the library, you can look into the source code. The dmt-klout library depends on the json.org classes to parse the JSON response. For instance:

public User(JSONObject json) {
    nick = json.getString("nick");
    id = new UserId(json.getString("kloutId"));
    JSONObject scores = json.getJSONObject("score");
    bucket = scores.getString("bucket");
    score = scores.getDouble("score");
    JSONObject scoreDeltas = json.getJSONObject("scoreDeltas");
    dayChange = scoreDeltas.getDouble("dayChange");
    weekChange = scoreDeltas.getDouble("weekChange");
    monthChange = scoreDeltas.getDouble("monthChange");
}

In this case json is a JSONObject created using the String that is returned when querying for a user. This User class is also used for the influence query:

public Influence(JSONObject json) {
    parseInfluence(json.getJSONArray("myInfluencers"), myInfluencers);
    parseInfluence(json.getJSONArray("myInfluencees"), myInfluencees);
}

private void parseInfluence(JSONArray array, List<User> list) {
    int count = array.length();
    for (int i = 0; i < count; i++) {
        list.add(new User(
            array.getJSONObject(i).getJSONObject("entity")
            .getJSONObject("payload")));
    }
}

Retrieving topics is done in a slightly different way:

public List<Topic> getTopics(UserId id) throws IOException {
    List<Topic> topics = new ArrayList<Topic>();
    JSONArray array = new JSONArray(KloutRequests.sendRequest(String.format(
            KloutRequests.TOPICS_FROM_KLOUT_ID, getUserId(id).getId(), apiKey)));
    int n = array.length();
    for (int i = 0; i < n; i++) {
        topics.add(new Topic(array.getJSONObject(i)));
    }
    return topics;
}

The constructor of the Topic class looks like this:

public Topic(JSONObject json) {
    id = json.getLong("id");
    name = json.getString("name");
    displayName = json.getString("displayName");
    slug = json.getString("slug");
    displayType = json.getString("displayType");
    imageUrl = json.getString("imageUrl");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜