Madhu
Madhu

Reputation: 5766

How to Convert Map to Object

I have a Map Object and the data in map is like

col1 -> data1, col2 -> data2, col3 -> data3 ...

Is it possible to convert this Map to Java Object like

class MapObj {

    String col1 = "data1";
    String col2 = "data2";
    String col3 = "data3";

}

Upvotes: 2

Views: 18218

Answers (6)

kai
kai

Reputation: 1768

use Jackson

import com.fasterxml.jackson.databind.ObjectMapper;

public class Foo {

  {
    ObjectMapper objectMapper = new ObjectMapper();
    YourObject obj = objectMapper.convertValue(YourMap, YourObject.class);
  }
}

Upvotes: 7

Stan Sokolov
Stan Sokolov

Reputation: 2260

BeanUtils.populate(entry,map);

Upvotes: 2

Hardcoded
Hardcoded

Reputation: 6494

I don't see any point in putting a bunch of Map values to a class. If you want static access, why not try the opposite:

class MapAccess {
  Map<String, String> backingMap = ...

  public String getCol1() {
    return backingMap.get("col1");
  }

  public String getCol2() {
    return backingMap.get("col2");
  }

  public String getCol3() {
    return backingMap.get("col3");
  }
}

This way, you'r application doesn't need to know about the Map and you don't get lost with reflection.

Upvotes: 0

Jim Ferrans
Jim Ferrans

Reputation: 31012

Are there a fixed set of named entries in the Map? If so, you can just create the MapObj class as you have it and assign the three fields by saying myMapObj.col1 = myMap.get("col1"); and so on.

But stepping back from this question for a moment, what's the larger problem you're trying to solve? A Map itself is actually a very convenient container for this data already, so perhaps you can just use the Map for the same purpose that you were planning to use MapObj for?

Upvotes: 1

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

Whilst it is possible to create classes at runtime with custom class loaders, it is relatively pointless. How would you access the fields (other than reflection and other dynamically created classes)?

Upvotes: 5

kylc
kylc

Reputation: 1363

I don't know of any pre-made libs that will do it for you, but it should be quite trivial using the java.lang.reflect API. Specifically, the Field#set* methods. Of course, however, you would need to have a pre-defined class with the fields (keys) defined.

Upvotes: 0

Related Questions