Json的拼装以及解析的简单工具

        java在当前传输过程中,json作为目前最广泛被接受的传输方式了,在小伙伴们编程的过程中肯定会遇到,我在最初的时候也是活遇到这个问题。为了获取到json字符串里面的对象信息,绞尽脑汁对字符串最处理。可是老是状态百出。

        现在搜集了,些许对json处理的方法,就算是新手的小伙伴们,也能无障碍使用。


一、下面是对于json和对象之间的转换的工具类:


import java.io.IOException;

import java.io.StringWriter;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * 对象和json数据转换类
 * @author Keen
 *
 */
public class PojoMapper {

    private static ObjectMapper m = new ObjectMapper();
    private static JsonFactory jf = new JsonFactory();

   

    /**
     * 将json字符串转换成对象
     * @param jsonAsString  json字符串
     * @param pojoClass     对象的泛型
     * @return   返回对象
     * @throws JsonMappingException
     * @throws JsonParseException
     * @throws IOException
     */

    public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass)
            throws JsonMappingException, JsonParseException, IOException {
        return m.readValue(jsonAsString, pojoClass);
    }
 
    
     /**
     * 将对象转换为json字符串
     * @param pojo   带转换的对象
     * @param prettyPrint   true/false 一般情况下选择false(注:这里是Boolean类型哦)
     * @param      
     *                     true的打印效果如下:
     *                     {
                              "id" : null,
                              .......
                            }
                            
                            false的打印效果如下:
     *                     {"id" : null,.......}
     *                 
     * @return   返回json字符串
     * @throws JsonMappingException
     * @throws JsonGenerationException
     * @throws IOException
     */
    public static String toJson(Object pojo, boolean prettyPrint)
            throws JsonMappingException, JsonGenerationException, IOException {
        StringWriter sw = new StringWriter();
        JsonGenerator jg = jf.createJsonGenerator(sw);
        if (prettyPrint) {
            jg.useDefaultPrettyPrinter();
        }
        m.writeValue(jg, pojo);
        return sw.toString();

    }

   

}

        通过上面的工具类,我们能够把对象和json字符串做很方便的转换,但是在实际开发过程中,json的字符串可能包含多个对象的数据信息,下面针对比较复杂的json字符串和对象之间做处理。

      倘若是下面的字符串,我们需要对其做业务上面的解析,拿出我们需要的信息,并且做出判断:


[{success:"true",infor:[{"id":"10002","userNumber":"Keen",......,"dept":{"id":10,"deptName":"市场部",......}},{......},{......}]}]

      上面的json字符串,在我们如果有三层信息:
1,success:true:表示该次操作是否成功,只有这里为true才会有数据;
2,infor里面是返回数据对象的信息;
3,user对象信息里面也包含有dept对象的信息(在转换成json的时候如何转换)


二、解析json字符串,取出对象信息;

/**
     * 通过api返回的json字符串,获取对象的list
     * @param json   api服务器返回的json数据字符串
     * @param clazz   对象的全限定名(用于规定list的对象泛型)
     * @return   返回装有对象的list
     */
    public static <T> List<T> getObject(String json, Class<T> clazz) {

        List<T> list = new ArrayList<T>();
        try {// 先判断是否获取数据成功
            JSONObject object = new JSONObject(json);
            if (json==null||"".equals(json)) {
                return null;
            }
            
            boolean booleans = object.getBoolean("success");
            if (booleans) {//判断是否数据成功,成功就转换数据
                JSONArray jsonArray = object.getJSONArray("infomation");
                List<Object> beanList;
                beanList = m.readValue(jsonArray.toString(),new TypeReference<List<Object>>() {});
                list = jsonToList(beanList.toArray(), clazz);
            } else {
                System.out.println("获取数据失败,返回空集合");
                return list;
            }
        } catch (Exception e) {
            System.out.println("对象数据获取错误");
            e.printStackTrace();
        }
        return list;
    }


三、对象在转换成json数据的时候,如果只是单一的对象,ok下面的可以不用再看,但是如果涉及到上述复杂的情形,可以使用map做拼装;

[{success:"true",infor:[{"id":"10002","userNumber":"Keen",......,"dept":{"id":10,"deptName":"市场部",......}},{......},{......}]}]
还是以这个json字符串为例:
 


拼接json的数据字符串:

response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");

PrintWriter out = response.getWriter();

JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();

//----------------------------准备好对象-------------------------------

user.......

//-----------------------------准备好装对象的map------------------------------

map.......


jo.accumulate("success", true);

ja.add(dateUtil.util(map));

jo.accumulate("infor", ja);


out.print(jo.toString());
out.flush();
out.close();


............................



//------------------------------------------------------------------------------------------

其中用到了的工具类:

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.Entity;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

@Entity
public class dateUtil
{
  public static JSONObject util(Object object)
  {
    JsonConfig cfg = new JsonConfig();
    cfg.registerJsonValueProcessor(Date.class,
      new JsonValueProcessor() {
      private final String format = "yyyy-MM-dd";

      public Object processObjectValue(String key, Object value, JsonConfig arg2)
      {
        if (value == null)
          return "";
        if (value instanceof Date) {
          String str = new SimpleDateFormat("yyyy-MM-dd")
            .format((Date)value);
          return str;
        }
        return value.toString();
      }

      public Object processArrayValue(Object value, JsonConfig arg1)
      {
        return null;
      }
    });
    JSONObject json = JSONObject.fromObject(object, cfg);
    return json;
  }
}


经过一些处理了一些后,json字符串就拼接好了。


恩!欢迎交流:[email protected](电邮)

发布了17 篇原创文章 · 获赞 6 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/keenstyle/article/details/43836289
今日推荐