30

I am facing issue while parsing JSON using jackson-core-2.7.3.jar You can get them from here http://repo1.maven.org/maven2/com/fasterxml/jackson/core/

My JSON File is

[
    {
        "Name":  "System Idle Process",
        "CreationDate":  "20160409121836.675345+330"
    },
    {
        "Name":  "System",
        "CreationDate":  "20160409121836.675345+330"
    },
    {
        "Name":  "smss.exe",
        "CreationDate":  "20160409121836.684966+330"
    }
]

and the Java Code is by which I am trying to parse this is

byte[] mapData = Files.readAllBytes(Paths.get("process.txt"));
Map<String,String> myMap = new HashMap<String, String>();
ObjectMapper objectMapper=new ObjectMapper();
myMap = objectMapper.readValue(mapData, HashMap.class);
System.out.println("Map is: "+myMap);

But upon execution I am getting the error

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.HashMap out of START_ARRAY token
 at [Source: [B@34ce8af7; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:216)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:873)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:869)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromEmpty(StdDeserializer.java:874)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:337)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2872)

I have tried searching over stackoverflow but couldnot find a matchable solution to this type of JSON.

Any help would be appreciated.

NOTE: This JSON mentioned here is different a JSON without Key , for the first element it has value directly and inside that value it has key:valuepair. I am not sure how do I access key:value pair which is inside a value.

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
Ashish
  • 1,309
  • 1
  • 11
  • 17
  • 3
    How do you expect a JSON array to be converted to a Java `HashMap`? – Savior Apr 09 '16 at 17:04
  • 1
    Possible duplicate of [Error converting JSON string to map in Java using Jackson](http://stackoverflow.com/questions/5018340/error-converting-json-string-to-map-in-java-using-jackson) – timbre timbre Apr 09 '16 at 17:05
  • Its not duplicate you should check JSON first and read the problem properly. – Ashish Apr 09 '16 at 17:51

6 Answers6

26

This exception is raised because you're trying to deserialize a List in a Map.

The solution is create a TypeReference of List<Map<String, Object>>:

List<Map<String, Object>> myObjects = 
          mapper.readValue(mapData , new TypeReference<List<Map<String, Object>>>(){});
freedev
  • 25,946
  • 8
  • 108
  • 125
  • 2
    Your solution is working, but How can we check whether the file is returning List or Map. As the above solution will fail for map. – Vishal Biradar Nov 11 '20 at 12:59
13

Create a simple pojo Class First

class MyClass
{
@JsonProperty
private String Name;
@JsonProperty
private String CreationDate;
}

and use this code...

byte[] mapData = Files.readAllBytes(Paths.get("process.txt"));

ObjectMapper objectMapper=new ObjectMapper();
//add this line  
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);    
List<MyClass> myObjects = mapper.readValue(mapData , new TypeReference<List<MyClass>>(){});

or

byte[] mapData = Files.readAllBytes(Paths.get("process.txt"));

ObjectMapper objectMapper=new ObjectMapper();
 //add this line  
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);    

List<MyClass> myObjects = mapper.readValue(mapData , mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));

myObjects will contains the List of MyClass. Now you can access this list as per your requirement.

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
  • 1
    Please go through the JSON file again Creating class MyClass wont work with this JSON. I need to know how do I write as it is a JSON without name – Ashish Apr 09 '16 at 17:20
  • what should i look into ? @AshishPatel – Vikrant Kashyap Apr 09 '16 at 17:23
  • 1
    The JSON file is value->key:value pair It doesnt have 1st level key pair if you look into it. So even if i create class MyClass upon execution it throws error Unrecognized field "Name" – Ashish Apr 09 '16 at 17:26
  • have you tried yet or not? just try if error came then only you should say. please try one test case atleast. @AshishPatel – Vikrant Kashyap Apr 09 '16 at 17:29
  • @AshishPatel That's why you convert to a `List` not to `MyClass`. – Savior Apr 09 '16 at 17:30
  • 1
    Yes, I have tried it Here is the error Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Name" (class testapps.MyProcess), not marked as ignorable (0 known properties: ]) – Ashish Apr 09 '16 at 17:46
  • 1
    @AshishPatel add getters and setters to your `testapps.MyProcess` class or add `@JsonProperty` above `Name` and `CreationDate` fields like this: `class MyProcess { @JsonProperty private String Name; @JsonProperty private String CreationDate; }` – varren Apr 09 '16 at 17:54
  • @AshishPatel I have edited my answer .. would you please try this code?? – Vikrant Kashyap Apr 09 '16 at 17:59
  • @varren It gives output like testapps.MyProcess@60addb54 testapps.MyProcess@3f2a3a5 testapps.MyProcess@4cb2c100 – Ashish Apr 09 '16 at 18:20
  • @varren You are great man It works! :) I created getter and setter methods after that – Ashish Apr 09 '16 at 18:23
  • @VikrantKashyap Thanks a lot, I have been struggling with this whole day, this worked like a charm! – Vacha Dave Dec 24 '19 at 20:33
11

It seem's that your file is representing a List of objects with Name and CreationDate fields.

So you have to just use List instead of HashMap to ObjectMapper, code is mentioned below:

List<HashMap> dataAsMap = objectMapper.readValue(mapData, List.class);
KrishnaSingh
  • 696
  • 1
  • 7
  • 12
6

Well, you are trying to convert an json string that contains array/list of objects into an object.

Ex: { "key": "value"} is the json you want to convert, but actually you are doing,

[{ "key": "value"}].

simple fix, is remove the first and last char from your string and try. Hope it helps;)

DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
Guru
  • 2,739
  • 1
  • 25
  • 27
3

Why not?

ObjectMapper mapper = new ObjectMapper();

Object obj = mapper.readValue(file, new TypeReference<Object>() {});
Dharman
  • 30,962
  • 25
  • 85
  • 135
alexandrubarbat
  • 197
  • 1
  • 4
0

Your JSON is not a Map, but a List of Maps. So replace this:

myMap = objectMapper.readValue(mapData, HashMap.class);

with this:

myMap = objectMapper.readValue(mapData, new TypeReference<List<Map<String, String>>>(){});

Or you can change the format of your JSON data...

Sunny
  • 83
  • 1
  • 7