java json和object互換

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;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章