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;
}
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值