parse json

package org.easense.sortmethods;

import java.io.IOException;
import java.io.StringWriter;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonJsonFactory
{
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static JacksonJsonFactory instance = new JacksonJsonFactory();
    private JacksonJsonFactory() {}
   
    public static JacksonJsonFactory getInstance() {
        return instance;
    }
   
    public String toJson(Object object) {
        if (object == null) {
            return null;
        }
        StringWriter writer = new StringWriter();
        try {
            JsonGenerator generator = new JsonFactory().createJsonGenerator(writer);
            objectMapper.writeValue(generator, object);
            return writer.toString();
        } catch (IOException e) {
           
        }
        return null;
    }
   
    public <T> T fromJson(String json, Class<T> clazz) {
        if (json == null || json.trim().equals("")) {
            return null;
        }
        try
        {
            JsonParser jsonParser = new JsonFactory().createJsonParser(json);
            return objectMapper.readValue(jsonParser, clazz);
        }
        catch (JsonParseException e)
        {
           
        }
        catch (JsonMappingException e)
        {
           
        }
        catch (IOException e)
        {
           
        }
        return null;
    }
   
    public static void main(String[] aa) {
        String a = getInstance().toJson(null);
        System.out.println(a);
    }
   
}

你可能感兴趣的:(json)