2

Are there any custom JSON to java object parsers to map json properties to Java object attributes through some configuration.

suppose I have class

class Person { String id; String name; String loc;}

My json String is

{name:"xy",id:12, address: {location: "abc"}}

I need map location.address of json to loc property of Person. We need to drive this mapping through config XML or prop file.

EDITED....

I am trying to have grammer or rules defined in property file such as:

address.location = loc
id = id
name = name

This is what I am thinking. Not sure how map complex types such as List, Map, etc

So my code would call a method

Person p = ObjectMapper.map(jsonData,Person.class,configuration)

and actual mapping is done is this way

class ObjectMapper {
public static <T> T map(String jsonData,Class<T> rootType, Map<String,String> rules) {

    T object = rootType.newInstance();
     // TODO: code to parse json using the rules 
     //and finally return object

    return (T) object;
}

This is what I am planning to do. Any help is appreciated. Thanks in Advance.

5
  • 1
    code.google.com/p/google-gson and more details: pragmateek.com/javajson-mapping-with-gson/… Commented Sep 29, 2014 at 15:00
  • Show us the code you have tried and describe what problems you have with it. Commented Sep 29, 2014 at 15:01
  • 1
    we can so same thing using Reflections. Commented Sep 30, 2014 at 6:42
  • ya I am trying use Reflection API with Generics Commented Sep 30, 2014 at 7:24
  • check answer, may it solve all of your problems. Commented Sep 30, 2014 at 8:25

2 Answers 2

2

Use following code.

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Test {

    public static void main(String... args) throws Exception{
        Map<String, String> rules = new HashMap<>();
        rules.put("address.location", "loc");
        rules.put("name", "name");
        rules.put("id", "id");

        String jsonData = "{name:'xy',id:'12', address: {location: 'abc'}, phones: ['a', 'b', 'c']}";

        Person person = (Person) map(jsonData, Person.class, rules);
        System.out.println(new Gson().toJson(person));
    }

    public static Object map(String jsonData, Class<?> rootType, Map<String, String> rules) throws Exception{
        Map<String, Object> genericMap = new HashMap<>();
        Type type = new TypeToken<Map<String, Object>>() {}.getType();
        genericMap = new Gson().fromJson(jsonData, type);

        Object object = rootType.newInstance();

        for (Map.Entry<String, String> entry : rules.entrySet()){
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();

            String keys[] = mapKey.split("\\.");
            Map<String, Object> obj = null;
            if(keys.length > 1){
                obj = (Map<String, Object>) genericMap.get(keys[0]);
                for(int i=1;i<keys.length-1;i++){
                    obj = (Map<String, Object>) obj.get(keys[i]);
                }
                // Method method = object.getClass().getDeclaredMethod("set" +  capitalize(mapValue) , String.class);
                // method.invoke(object, (String)obj.get(keys[keys.length-1]));
                Field field = object.getClass().getDeclaredField(mapValue);
                field.set(object, obj.get(keys[keys.length - 1]));
            }else{
                // Method method = object.getClass().getDeclaredMethod("set" +  capitalize(mapValue) , String.class);
                // method.invoke(object, (String)genericMap.get(mapValue));

                Field field = object.getClass().getDeclaredField(mapValue);
                field.set(object, genericMap.get(mapValue));
            }
        }
        return object;
    }

    public static  String capitalize(String line){
      return Character.toUpperCase(line.charAt(0)) + line.substring(1);
    }
}

class Person {
    String id;
    String name;
    String loc;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }

}

Output

{"id":"12","name":"xy","loc":"abc","phones":["a","b","c"]}

Details

  • Used Gson API.
  • This code works for n number referenced object (like a.b.c.item).
  • Your class should contain getter/setter for each field.
  • Field name of Rules and POJO should match.
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for sharing the code. Would this work for even List, Map and Complex type(such as Person has some ProfessionDetails). Suppose I have a list of phone number object phoneNumber with fields exchange code, subscriber number and need map to list property of Person Object.How should I define my rules in this case. I was thinking to define like L->phonenumbers.exchangecode = L-> phonenumbers.exchangecode. L represents List. C
currently i assuming your all fields of type String, see ("set" + capitalize(mapValue) , String.class). but you can give a datatype using reflections. i tried for List also.
changed a code to support collections, now you have to change a parser according to your requirement. you can create your own parser depend on your requirement.
-1

Import this library to your project code.google.com/p/google-gson

Afterwards, it is possible to do this: ("json" is whatever json-String you want to parse in. It could be the one you specified in your question.)

Person personFromJson = new Gson().fromJson(json, Person.class);

1 Comment

I don't think that the OP's example can be handled that easily given that there is no 1-to-1 mapping of attributes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.