GVKun编程网logo

fastjson list转json(fastjson list转json字符串)

22

本文将带您了解关于fastjsonlist转json的新内容,同时我们还将为您解释fastjsonlist转json字符串的相关知识,另外,我们还将为您提供关于com.alibaba.fastjson

本文将带您了解关于fastjson list转json的新内容,同时我们还将为您解释fastjson list转json字符串的相关知识,另外,我们还将为您提供关于com.alibaba.fastjson.JSONException: syntax error, expect {, actual iso8601, pos 266, fastjson-versio、com.alibaba.fastjson.support.spring.FastJsonJsonView的实例源码、fastjson com.alibaba.fastjson.JSONException: unclosed string : 十、fastjson json 解析 List 返回 null 异常的实用信息。

本文目录一览:

fastjson list转json(fastjson list转json字符串)

fastjson list转json(fastjson list转json字符串)

pom.xml文件中加入依赖依赖:
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.0.4</version>
</dependency>

如果没有使用maven,可以直接下载:
http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.0.4/fastjson-1.0.4.jar
http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.0.4/fastjson-1.0.4-sources.jar


使用介绍:
Fastjson的最主要的使用入口是com.alibaba.fastjson.JSON

import com.alibaba.fastjson.JSON;

public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文本parse为JavaBean
public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文本parse成JavaBean集合
public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray。

com.alibaba.fastjson.JSONException: syntax error, expect {, actual iso8601, pos 266, fastjson-versio

com.alibaba.fastjson.JSONException: syntax error, expect {, actual iso8601, pos 266, fastjson-versio

这个问题的解决需要 @JSONField (format="yyyy-MM-dd") private Date createDate;

com.alibaba.fastjson.support.spring.FastJsonJsonView的实例源码

com.alibaba.fastjson.support.spring.FastJsonJsonView的实例源码

项目:GitHub    文件:FastJsonjsonViewTest.java   
@Test
public  void test_jsonp() throws Exception {
    FastJsonjsonView view = new FastJsonjsonView();

    Assert.assertNotNull(view.getFastJsonConfig());
    view.setFastJsonConfig(new FastJsonConfig());
    view.setExtractValueFromSingleKeyModel(true);
    view.setdisableCaching(true);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("callback","queryName");
    MockHttpServletResponse response = new MockHttpServletResponse();


    Assert.assertEquals(true,view.isExtractValueFromSingleKeyModel());


    view.render(Collections.singletonMap("abc","cde中文"),request,response);
    String contentAsstring = response.getContentAsstring();
    int contentLength = response.getContentLength();

    Assert.assertEquals(contentLength,contentAsstring.getBytes(view.getFastJsonConfig().getCharset().name()).length);
}
项目:TBSpider    文件:IndexController.java   
@RequestMapping(value = "/getProgress/{fileKey}",method = RequestMethod.GET)
public ModelAndView getProgress(@PathVariable("fileKey") String fileKey,Map<String,Object> model) {
    if (PROCESS_MAP.containsKey(fileKey)) {
        Tuple2Unit<Integer,Integer> progresstuple = PROCESS_MAP.get(fileKey);
        model.put("status","processing");
        model.put("precent",progresstuple.getP1() * 100 / progresstuple.getP2());
    } else {
        model.put("status","OK");
    }
    return new ModelAndView(new FastJsonjsonView());
}
项目:GitHub    文件:Issue1405.java   
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
    FastJsonjsonView fastJsonjsonView = new FastJsonjsonView();
    registry.enableContentNegotiation(fastJsonjsonView);
}
项目:GitHub    文件:FastJsonjsonViewTest.java   
@SuppressWarnings("deprecation")
  public void test_0() throws Exception {
      FastJsonjsonView view = new FastJsonjsonView();

      Assert.assertEquals(Charset.forName("UTF-8"),view.getCharset());
      view.setCharset(Charset.forName("GBK"));
      Assert.assertEquals(Charset.forName("GBK"),view.getCharset());

      Assert.assertNull(view.getDateFormat());
      view.setDateFormat("yyyyMMdd");

      Assert.assertNotNull(view.getFeatures());
      Assert.assertEquals(1,view.getFeatures().length);

      view.setSerializerFeature(SerializerFeature.browserCompatible);
      Assert.assertEquals(1,view.getFeatures().length);
      Assert.assertEquals(SerializerFeature.browserCompatible,view.getFeatures()[0]);

      view.setFeatures(SerializerFeature.disableCheckSpecialChar,SerializerFeature.sortField);
      Assert.assertEquals(2,view.getFeatures().length);
      Assert.assertEquals(SerializerFeature.disableCheckSpecialChar,view.getFeatures()[0]);
      Assert.assertEquals(SerializerFeature.sortField,view.getFeatures()[1]);

      view.setFilters(serializefilter);
Assert.assertEquals(1,view.getFilters().length);
Assert.assertEquals(serializefilter,view.getFilters()[0]);

      Map<String,Object> model = new HashMap<String,Object>();
      MockHttpServletRequest request = new MockHttpServletRequest();
      MockHttpServletResponse response = new MockHttpServletResponse();
      view.render(model,response);

      view.setRenderedAttributes(null);

      view.setCharset(Charset.forName("UTF-8"));
      view.render(model,response);

      view.setUpdateContentLength(true);
      view.setFeatures(SerializerFeature.browserCompatible);
      view.render(model,response);

      view.setCharset(Charset.forName("GBK"));
      view.render(Collections.singletonMap("abc","cde"),response);

      view.setdisableCaching(false);
      view.setUpdateContentLength(false);
      view.render(model,response);

      view.setRenderedAttributes(new HashSet<String>(Collections.singletonList("abc")));
      view.render(Collections.singletonMap("abc",response);

  }
项目:GitHub    文件:FastJsonjsonViewTest.java   
public void test_1() throws Exception {

    FastJsonjsonView view = new FastJsonjsonView();

    Assert.assertNotNull(view.getFastJsonConfig());
    view.setFastJsonConfig(new FastJsonConfig());

    Map<String,Object>();
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    view.render(model,response);

    view.setRenderedAttributes(null);
    view.render(model,response);

    view.setUpdateContentLength(true);
    view.render(model,response);

    view.setExtractValueFromSingleKeyModel(true);
    Assert.assertEquals(true,view.isExtractValueFromSingleKeyModel());

    view.setdisableCaching(true);
    view.render(Collections.singletonMap("abc",response);

}
项目:GitHub    文件:FastJsonjsonViewTest.java   
@Test
public  void test_jsonp_invalidparam() throws Exception {
    FastJsonjsonView view = new FastJsonjsonView();

    Assert.assertNotNull(view.getFastJsonConfig());
    view.setFastJsonConfig(new FastJsonConfig());
    view.setExtractValueFromSingleKeyModel(true);
    view.setdisableCaching(true);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("callback","-methodName");
    MockHttpServletResponse response = new MockHttpServletResponse();


    Assert.assertEquals(true,view.isExtractValueFromSingleKeyModel());


    view.render(Collections.singletonMap("doesn't matter",Collections.singletonMap("abc","cde中文")),response);
    String contentAsstring = response.getContentAsstring();
    Assert.assertTrue(contentAsstring.startsWith("{\"abc\":\"cde中文\"}"));

}

fastjson com.alibaba.fastjson.JSONException: unclosed string : 十

fastjson com.alibaba.fastjson.JSONException: unclosed string : 十

使用fastjson在转换的时候,

com.alibaba.fastjson.JSONException: unclosed string : 十
    at com.alibaba.fastjson.parser.JSONLexerBase.scanString(JSONLexerBase.java:1001)
    at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:485)
    at com.alibaba.fastjson.parser.DefaultJSONParser.parse(DefaultJSONParser.java:1407)
    at com.alibaba.fastjson.parser.DefaultJSONParser.parse(DefaultJSONParser.java:1373)
    at com.alibaba.fastjson.JSON.parse(JSON.java:182)
    at com.alibaba.fastjson.JSON.parse(JSON.java:192)
    at com.alibaba.fastjson.JSON.parse(JSON.java:148)






    /**
     * 因为key之前多了个 \ 导致解码失败了。
     * 不管多少个反斜杠,简单粗暴的给他全替换了得了
     * StringEscapeUtils.unescapeJavaScript(json);
     * 这个不太好使。
     */
    @Test
    public void unclosedString2() {
        String json = "{\"s.os\":\"李\\\\\\\\\\\\学\\十大!@#$%^&*()))_+{}:?><{}][|||||{{{}}}}[][][][[[]]]:::;;;''''''''''''\\~`表代表///23456...#\",\"ssass\":\"\",\"lxk\":123467987654345}";
        System.out.println(json);
        //Map 类可以, hash map 不 OK。
        Map map = JsonUtils.parseJsonToObj(json, Map.class);
        System.out.println(map);
    }

    public static <T> T parseJsonToObj(String json, Class<T> c) {
        try {
            JSONObject jsonObject = JSON.parseObject(json);
            return JSON.toJavaObject(jsonObject, c);
        } catch (Exception e) {
            try {
                //String s = StringEscapeUtils.unescapeJavaScript(json);
                String s = json.replace("\\", "");
                JSONObject jsonObject = JSON.parseObject(s);
                return JSON.toJavaObject(jsonObject, c);
            } catch (Exception ee) {
                System.out.println(ee.getMessage());
            }
        }
        return null;
    }

说是升级jar包版本能解决,但是好像不行,我试过  ''1.2.73''这个了还是不行,最后还又说使用 StringEscapeUtils.unescapeJavaScript(json) 这个来,其实就是把反斜杠给替换掉了,这个apach的common lang包里面的,要是有这个依赖的话,直接可以使用,要没的话,就简单的字符串替换解决吧,最好是能吧json中的反斜杠给干掉。

fastjson json 解析 List 返回 null 异常

fastjson json 解析 List 返回 null 异常

前端说  获取 List 数据,返回的是 null 而不是 空数组 [ ] 这就奇怪了, 明明 配置类 全局的 json 配置啊, List 对象会 null 会转成 空数组

  @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {


        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                // 防止循环引用
                SerializerFeature.DisableCircularReferenceDetect,
                // 空集合返回[],不返回null
                SerializerFeature.WriteNullListAsEmpty,
                // 空字符串返回"",不返回null
//                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteMapNullValue
        );
        fastJsonConfig.setDateFormat(DatePattern.NORM_DATETIME_PATTERN);//时间格式
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);

        //支持的类型。 不需要配置,默认已经支持所有的类型了
//        List<MediaType> fastMediaTypes = new ArrayList<>();
//        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//        fastMediaTypes.add(MediaType.APPLICATION_JSON);
//        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);

        fastJsonHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));

        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        //解决Controller的返回值为String时,中文乱码问题
        stringConverter.setDefaultCharset(Charset.forName("UTF-8"));
        //解决视图的返回值类型为String时,返回的string字符串带有双引号问题,先执行字符转换
        converters.add(0, stringConverter);

        //使springmvc优先使用fastjson  处理除了 string 类型 所有的数据. 一般也都是 json 格式的数据. 同时提高处理速度
        converters.add(1, fastJsonHttpMessageConverter);

        ParserConfig.getGlobalInstance().setAutoTypeSupport(true); // 开启AutoType
        ParserConfig.getGlobalInstance().addAccept("*"); //设置白名单
    }

解决办法

结果测试 发现 如果 entity 里面的 List 才会生效。 而 如果 直接 返回 数组是不行的

因此只能在 返回 Result 上 判断了


 public static Result success(String msg, Object data) {
    return new Result(Code.ReqSuccess, msg, data);
  }

  public static Result success(String msg, List data) {
    if (data == null) {
      // 避免 list  出去前端的时候 null 变成 [] 而不是 null
      data = new ArrayList();
    }
    return new Result(Code.ReqSuccess, msg, data);
  }


@ApiOperation(value = "获取应用系统的菜单权限", notes = "根据主键id,获取应用系统的菜单权限")
  @ApiImplicitParam(name = "ids", value = "主键Id", dataType = "Long", paramType = "query")
  @RequestMapping(value = "/ac/admin/app/acAppMenu/listByIds", method = RequestMethod.POST)
  public Result<List<AcAppMenu>> listByIds(@RequestBody IdsParamVo vo) {
    PreconditionsUtils.checkNotNull(vo.getIds(), "ids不能为空");

    List<AcAppMenu> list =
        (List<AcAppMenu>) acAppMenuService.listByIds(CollUtil.toList(vo.getIds()));
    return Result.success("获取成功", list); // 这样就算是 List  null 也会返回 空数组
  }

关于fastjson list转jsonfastjson list转json字符串的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于com.alibaba.fastjson.JSONException: syntax error, expect {, actual iso8601, pos 266, fastjson-versio、com.alibaba.fastjson.support.spring.FastJsonJsonView的实例源码、fastjson com.alibaba.fastjson.JSONException: unclosed string : 十、fastjson json 解析 List 返回 null 异常等相关内容,可以在本站寻找。

本文标签: