All Downloads are FREE. Search and download functionalities are using the official Maven repository.

spinjar.com.jayway.jsonpath.spi.mapper.JsonOrgMappingProvider Maven / Gradle / Ivy

There is a newer version: 7.22.0-alpha5
Show newest version
package com.jayway.jsonpath.spi.mapper;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.TypeRef;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonOrgMappingProvider implements MappingProvider {
    @Override
    public  T map(Object source, Class targetType, Configuration configuration) {
        if(source == null){
            return null;
        }
        if(targetType.equals(Object.class) || targetType.equals(List.class) || targetType.equals(Map.class)){
            return (T) mapToObject(source);
        }
        return (T)source;
    }

    @Override
    public  T map(Object source, TypeRef targetType, Configuration configuration) {
        throw new UnsupportedOperationException("JsonOrg provider does not support TypeRef! Use a Jackson or Gson based provider");
    }


    private Object mapToObject(Object source){
        if(source instanceof JSONArray){
            List mapped = new ArrayList();
            JSONArray array = (JSONArray) source;

            for (int i = 0; i < array.length(); i++){
                mapped.add(mapToObject(array.get(i)));
            }

            return mapped;
        }
        else if (source instanceof JSONObject){
            Map mapped = new HashMap();
            JSONObject obj = (JSONObject) source;

            for (Object o : obj.keySet()) {
                String key = o.toString();
                mapped.put(key, mapToObject(obj.get(key)));
            }
            return mapped;
        }
        else if (source == JSONObject.NULL){
            return null;
        } else {
            return source;
        }
    }
}