Mapping JSON data to Java objects

前端 未结 2 1244
南旧
南旧 2021-01-14 13:54

I have been trying to map JSON data to Java objects, with the JSON file on my PC, but it always throws the exception:

org.codehaus.jackson.map.exc.Unrecognized

2条回答
  •  北海茫月
    2021-01-14 13:57

    Here is a list of problems I see in your code:

    1. The @JsonIgnoreProperties attribute should be put above the MovieResponse class, not the Movie class. Check out the documentation, most notably what is said about the "ignoreUnknown" property, defaulted to false:

      public abstract boolean ignoreUnknown

      Property that defines whether it is ok to just ignore any unrecognized properties during deserialization. If true, all properties that are unrecognized -- that is, there are no setters or creators that accept them -- are ignored without warnings (although handlers for unknown properties, if any, will still be called) without exception.

    2. Your setters should not return any value, this may explain why Jackson does not see a "title" setter. Here is how the setter for "title" should be:

      public void setTitle(String t) {
          title = t;
      }
      
    3. Not a reason for it to NOT work, but you are declaring your object mapper twice, consider using your mapper instead of instanciating a new one:

      MovieResponse response = mapper.readValue(new File("C:\\M.json"), MovieResponse.class);
      

    Edit: here's your fixed code I think:

    import java.io.File;
    import org.codehaus.jackson.map.ObjectMapper;
    import java.net.*;
    import org.codehaus.jackson.annotate.JsonIgnoreProperties;
    
    public class Movie {
        public static void main(String[] args) throws Exception {
            MovieResponse response;
            ObjectMapper mapper = new ObjectMapper();
    
            response = mapper.readValue(new File("C:\\M.json"), MovieResponse.class);
            System.out.println(response);
        }
    }
    

提交回复
热议问题