tags:

views:

1015

answers:

3

This is my first time trying to do something useful with Java.. I'm trying to do something like this but it doesn't work:

Map<String, String> propertyMap = new HashMap<String, String>();

propertyMap = JacksonUtils.fromJSON(properties, Map.class);

But the IDE says: 'Unchecked assignment Map to Map<String,String>'

What's the right way to do this? I'm only using Jackson because that's what is already available in the project, is there a native Java way of converting to/from JSON?

In PHP I would simply json_decode($str) and I'd get back an array. I need basically the same thing here.

Thanks!

+5  A: 

I've got code of this kind

public void testJackson() throws IOException {        
    JsonFactory factory = new JsonFactory(); 
    ObjectMapper mapper = new ObjectMapper(factory); 
    File from = new File("albumnList.txt"); 
    TypeReference<HashMap<String,Object>> typeRef 
          = new TypeReference< 
                 HashMap<String,Object> 
               >() {}; 
    HashMap<String,Object> o 
         = mapper.readValue(from, typeRef); 
    System.out.println("Got " + o); 
}    

There's a bit more explantion on my blog.

djna
This sounds like what I need, let me try it out thx
Infinity
+1  A: 

Warning you get is done by compiler, not by library (or utility method).

Simplest way using Jackson directly would be:

HashMap<String,Object> props;

// src is a File, InputStream, String or such
props = new ObjectMapper().readValue(src, new TypeReference<HashMap<String,Object>>() {});
// or:
props = (HashMap<String,Object>) new ObjectMapper().readValue(src, HashMap.class);
// or even just:
@SuppressWarnings("unchecked") // suppresses typed/untype mismatch warnings, which is harmless
props = new ObjectMapper().readValue(src, HashMap.class);

Utility method you call probably just does something similar to this.

StaxMan
+2  A: 

Try TypeFactory

Map<String, String> result = new ObjectMapper().readValue(
    data, TypeFactory.mapType(HashMap.class, String.class, String.class));
Sunng