2
votes

Comment puis-je parcourir des objets JSON à l'aide de Jackson?

Je souhaite finalement créer des index inversés à l'aide de mon ensemble de données JSON. Je sais comment analyser un objet JSON, mais comment puis-je en parcourir plusieurs? Voici ce que je travaille:

File1:

[
    {
        "doc_id": "2324jos",
        "screen_name": "b'LIBBYRULZ'",
        "tweet_text": "@ABC ya'll be lying",
        "hashtags": "[]",
        "links": "[]",
        "place_type": "city",
        "place_name": "Evergreen Park",
        "created_at": "2019-02-08 22:24:03"
    },
    {
        "doc_id": "8982hol",
        "screen_name": "b'eddylee_1'",
        "tweet_text": "Hungry for money",
        "hashtags": "[]",
        "links": "[]",
        "place_type": "city",
        "place_name": "Manhattan",
        "created_at": "2/7/2019 17:01"
    }
]     

Mon code:

public class ParseJson {
    public static void main(String[] args) throws Exception {
        // this is the key object to convert JSON to Java
        Tweet tweet;
        ObjectMapper mapper = new ObjectMapper();
        try {
            File json = new File("test.json");
            tweet = mapper.readValue(json, Tweet.class);
            System.out.println("Java object created from JSON String :");
            System.out.println(tweet);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

public class Tweet {
    public String doc_id;
    public String screen_name;
    public String tweet_text;
    public String hashtags;
    public String links;
    public String place_type;
    public String place_name;
    public String created_at;

    public Tweet() {

    }

    public Tweet(String doc_id, String screen_name, String tweet_text, String hashtags, String links, String place_type, String place_name, String created_at) {
        this.doc_id = doc_id;
        this.screen_name = screen_name;
        this.tweet_text = tweet_text;
        this.hashtags = hashtags;
        this.links = links;
        this.place_name = place_name;
        this.place_type = place_type;
        this.created_at = created_at;
    }

    @Override
    public String toString() {
        return doc_id + screen_name + tweet_text;
    }
}

Maintenant, je veux Parcourez ce fichier JSON qui contient 2 objets JSON dans un tableau:

File2:

{
    "doc_id": "2324jos",
    "screen_name": "twitter_user101",
    "tweet_text": "Its a beautiful day to be productive",
    "hashtags": "[]",
    "links": "[]",
    "place_type": "city",
    "place_name": "Evergreen Park",
    "created_at": "2019-02-08 22:24:03"
}

Comment puis-je ajuster mon code ci-dessus en utilisant Jackson pour le faire où doc_id est la clé unique? Je veux pouvoir renvoyer toutes les données de chaque objet JSON pour chaque doc_id.


0 commentaires

3 Réponses :


4
votes

Pour analyser un tableau d'objets JSON en utilisant Jackson:

public class ParseJson {
    public static void main(String[] args) throws Exception {

        Tweet[] tweets;
        ObjectMapper mapper = new ObjectMapper();
        try {
            File json = new File("test.json");
            tweets = mapper.readValue(json, Tweet[].class);
            System.out.println("Java object created from JSON String :");
            Arrays.asList(tweets).forEach(System.out::println); // Prints each element in the array
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

devrait faire l'affaire. Voir ci-dessous:

Tweet[] tweets = mapper.readValue(json, Tweet[].class);


4 commentaires

Merci - pouvez-vous le montrer peut-être avec un peu plus de contexte - J'obtiens une erreur: org.codehaus.jackson.map.JsonMappingException: impossible de désérialiser l'instance de Tweet à partir du jeton START_ARRAY


Vous obtenez cette exception car vous essayez de mapper un tableau JSON à un objet Java. Vous devez mapper le tableau JSON à une liste d'objets java ou à un tableau d'objets java.


Merci Matt - J'ai encore des problèmes, pouvez-vous reproduire le code ci-dessus avec vos modifications? Si c'est le cas, je marquerai ceci comme la réponse acceptée :)


Je viens d'ajouter votre classe ParseJson à la réponse ci-dessus!



3
votes

Vous pouvez essayer de le mettre dans une liste afin de pouvoir le parcourir:

List<Tweet> data = mapper.readValue(json, new TypeReference<List<Tweet>>(){});


0 commentaires

2
votes

Je suggérerais d'utiliser TypeFactory pour créer un CollectionType et l'utiliser pour analyser le JSON en tant que List .

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ParseJson {
    public static void main(String[] args) {
        // this is the key object to convert JSON to Java
        ObjectMapper mapper = new ObjectMapper();
        try {
            File json = new File("test.json");
            CollectionType tweetListType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Tweet.class);
            List<Tweet> tweets = mapper.readValue(json, tweetListType);
            System.out.println("Java objects created from JSON String:");
            tweets.forEach(System.out::println);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Voici l'exemple complet que vous avez partagé:

CollectionType tweetListType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Tweet.class);
List<Tweet> tweets = mapper.readValue(json, tweetListType);
tweets.forEach(System.out::println);


3 commentaires

quel est l'import pour cela?


Importation de CollectionType? import com.fasterxml.jackson.databind.type.CollectionType;


génial merci, cela a fonctionné et a amélioré ma compréhension du type de collection!