Cakestep
Cakestep

Reputation: 111

Java json parse

Well I've been trying for like 3 hours now. Using lots of apis it still doesn't work.

I'm trying to parse

{
  "id": 8029390,
  "uid": "fdABNhroHsr0",
  "user": {
    "username": "Skrillex",
    "permalink": "skrillex"
  },
  "uri": "/skrillex/cat-rats",
  "duration": 305042,
  "token": "VgA2a",
  "name": "cat-rats",
  "title": "CAT RATS",
  "commentable": true,
  "revealComments": true,
  "commentUri": "/skrillex/cat-rats/comments/",
  "streamUrl": "http://media.soundcloud.com/stream/fdABNhroHsr0?stream_token=VgA2a",
  "waveformUrl": "http://w1.sndcdn.com/fdABNhroHsr0_m.png",
  "propertiesUri": "/skrillex/cat-rats/properties/",
  "statusUri": "/transcodings/fdABNhroHsr0",
  "replacingUid": null,
  "preprocessingReady": null
}

in to an array/list. Any help?

Upvotes: 3

Views: 5048

Answers (2)

mdeanda
mdeanda

Reputation: 185

You should try JavaJson from source forge... you can parse that this way:

JsonObject json = JsonObject.parse("...");
/*
 * or also JsonObject.parse(inputStream);
 */
then you can get fields this way:
String title = json.getString("title");
String username = json.get("user", "username").toString();

and so on. here's the link: https://sourceforge.net/projects/javajson/

Upvotes: 1

Francisco Paulo
Francisco Paulo

Reputation: 6322

I'm using Jackson from http://codehaus.org/ and so far it has lived up to all my needs.

You don't quite deal with json as raw strings in an arraylist, but rather as POJOs, here's a quick example with a subset of your json.

public class JacksonExample {
    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        String text = "{ \"id\": 8029390, \"user\": { \"username\": \"Skrillex\" } }";

        ObjectMapper mapper = new ObjectMapper();
        Pojo pojo = mapper.readValue(text, Pojo.class);

        System.out.println(pojo.id);
        System.out.println(pojo.user.username);
    }
}

class Pojo {
    public String id;
    public User user;

    public String getId() { return id; }
    public void setId(String id) { this.id = id; }

    public User getUser() { return user; }
    public void setUser(User user) { this.user = user; }

    public static class User {
        public String username;

        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
    }
}

The mapper creates a Pojo object with the values filled in. Then you can use that object for anything you need.

Here are a couple of links for the Jackson project:

http://jackson.codehaus.org/

http://wiki.fasterxml.com/JacksonInFiveMinutes

The latest all in one JAR is here:

http://jackson.codehaus.org/1.9.1/jackson-all-1.9.1.jar

Upvotes: 6

Related Questions