现在的位置: 首页 > 综合 > 正文

java json和object互换

2013年12月03日 ⁄ 综合 ⁄ 共 1781字 ⁄ 字号 评论关闭
package com.help;


import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;


import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


public class JsonFunc {
static ObjectMapper mapper = new ObjectMapper();


public static String toJSON(Object obj) {
     StringWriter writer = new StringWriter();
     try {
        mapper.writeValue(writer, obj);
     } catch (JsonGenerationException e) {
        throw new RuntimeException(e);
     } catch (JsonMappingException e) {
        throw new RuntimeException(e);
     } catch (IOException e) {
        throw new RuntimeException(e);
     }
     return writer.toString();
}

public static <T> T fromJSON(String json, Class<T> clazz) {
     ObjectMapper mapper = new ObjectMapper();
     try {
        return mapper.readValue(json, clazz);
     } catch (JsonParseException e) {
        throw new RuntimeException(e);
     } catch (JsonMappingException e) {
        throw new RuntimeException(e);
     } catch (IOException e) {
        throw new RuntimeException(e);
     }
  }
public static <T> T fromJSON(InputStream json, Class<T> clazz) {
     ObjectMapper mapper = new ObjectMapper();
     try {
        return mapper.readValue(json, clazz);
     } catch (JsonParseException e) {
        throw new RuntimeException(e);
     } catch (JsonMappingException e) {
        throw new RuntimeException(e);
     } catch (IOException e) {
        throw new RuntimeException(e);
     }
  }
public static List<String> getJsonList(String jstr,List<String> li)
{
char[] cstr = jstr.toCharArray();
boolean bend = false;
int istart =0;
int iend =0;
for(int i=0 ; i < cstr.length; i++)
{
if ((cstr[i] == '{') && !bend)
{
istart = i;
}
if (cstr[i] == '}' && !bend)
{
iend = i;
bend = true;
}
}

if (istart !=0)
{
 String substr = jstr.substring(istart, iend+1);
 jstr = jstr.substring(0,istart-1) + jstr.substring(iend+1,jstr.length());
 substr = substr.replace(",\"children\":", "");
 substr = substr.replace("]", "");
 substr = substr.replace("[", "");
  li.add(substr);
  getJsonList(jstr,li);
}
return li;
}
}

抱歉!评论已关闭.