使用Flexjson时如何排除空值字段?

发布于 2024-12-12 04:41:38 字数 568 浏览 0 评论 0原文

我正在使用 Flexjson 将这样的类序列化为 JSON:

public class Item {
    private Long id;
    private String name;
    private String description;
    ...

    // Getters and setters
    ...
}

许多 Item 字段可以为 null(例如,描述)。因此,当使用 Flexjson 序列化此类 Item 对象时,我会得到以下 JSON:

 {"id":62,"name":"Item A","description":null,...}

正如我已经提到的,由于 Item 对象可能包含许多空值字段,因此输出的 JSON 比实际需要的长度要长。到目前为止,这是一个问题,因为我想通过 WiFi、3G、EDGE 或 GPRS 通过无线连接将生成的 JSON 从 Web 服务器发送到移动客户端(即需要更多带宽,这会导致速度降低) )。

因此,我想问如何使用 Flexjson (有效)排除空值属性?

谢谢!

I am serializing a class like this into JSON using Flexjson:

public class Item {
    private Long id;
    private String name;
    private String description;
    ...

    // Getters and setters
    ...
}

Many of the Item fields can be null (e.g., description). Consequently, when such an Item object is serialized using Flexjson, I get the following JSON:

 {"id":62,"name":"Item A","description":null,...}

Since, as I already mentioned, an Item object may contain many null-value fields, the outcoming JSON is longer than effectively needed. This is in so far a problem, because I would like to send the generated JSON from a web server to a mobile client over a wireless connection via WiFi, 3G, EDGE or GPRS (i.e., more bandwidth is required, which results in less speed).

Therefore, I wanted to ask how it is possible to (efficiently) exclude null-value attributes using Flexjson?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

红ご颜醉 2024-12-19 04:41:38

您可以使用以下转换器:

import flexjson.transformer.AbstractTransformer;

public class ExcludeTransformer extends AbstractTransformer {

  @Override
  public Boolean isInline() {
      return true;
  }

  @Override
  public void transform(Object object) {
      // Do nothing, null objects are not serialized.
      return;
  }
}

具有以下用法:

new JSONSerializer().transform(new ExcludeTransformer(), void.class).serialize(yourObject)

请注意,所有空字段都将被排除。

不支持按路径(相对于类)添加转换器,因为 FlexJSON 强制 TypeTransformer 为空值:

JSONContext.java:第 95 行:

private Transformer getPathTransformer(Object object) {
    if (null == object) return getTypeTransformer(object);
    return pathTransformerMap.get(path);
}

You can use the following transformer :

import flexjson.transformer.AbstractTransformer;

public class ExcludeTransformer extends AbstractTransformer {

  @Override
  public Boolean isInline() {
      return true;
  }

  @Override
  public void transform(Object object) {
      // Do nothing, null objects are not serialized.
      return;
  }
}

with the following usage :

new JSONSerializer().transform(new ExcludeTransformer(), void.class).serialize(yourObject)

Note that all null fields will be excluded.

Adding the Transformer by Path (vs by Class) is not supported as FlexJSON forces TypeTransformer for null values :

JSONContext.java : line 95 :

private Transformer getPathTransformer(Object object) {
    if (null == object) return getTypeTransformer(object);
    return pathTransformerMap.get(path);
}
情仇皆在手 2024-12-19 04:41:38

我是一个新手,我遇到了同样的问题,在 Source Forge 上找不到任何解决方案,所以我使用正则表达式从 JSON 字符串中删除所有空值

/**
 * This Function removes all the key:value pairs from the Json String for which the value equals null
 * @param jsonStringWithNullKeys
 * @return jsonStringWithoutNullKeys
 */
public static String getJsonStringWithoutNullKeys(String jsonStringWithNullKeys)
{
    Pattern p = Pattern.compile( "([,]?\"[^\"]*\":null[,]?)+" );
    Matcher m = p.matcher( jsonStringWithNullKeys );
    StringBuffer newString = new StringBuffer( jsonStringWithNullKeys.length() );

    while( m.find() )
    {
        if( m.group().startsWith( "," ) & m.group().endsWith( "," ) ) m.appendReplacement( newString, "," );
        else
            m.appendReplacement( newString, "" );
    }
    m.appendTail( newString );
    return newString.toString();
}

I am a newbie,i had same problem and could not find any solution on source forge so i used regular expression to remove all the nulls from JSON String

/**
 * This Function removes all the key:value pairs from the Json String for which the value equals null
 * @param jsonStringWithNullKeys
 * @return jsonStringWithoutNullKeys
 */
public static String getJsonStringWithoutNullKeys(String jsonStringWithNullKeys)
{
    Pattern p = Pattern.compile( "([,]?\"[^\"]*\":null[,]?)+" );
    Matcher m = p.matcher( jsonStringWithNullKeys );
    StringBuffer newString = new StringBuffer( jsonStringWithNullKeys.length() );

    while( m.find() )
    {
        if( m.group().startsWith( "," ) & m.group().endsWith( "," ) ) m.appendReplacement( newString, "," );
        else
            m.appendReplacement( newString, "" );
    }
    m.appendTail( newString );
    return newString.toString();
}
青萝楚歌 2024-12-19 04:41:38

我还没有确切地尝试过您的情况,但我相信以下内容应该可以解决您的问题:

Item item;
// Assign item here
JSONSerializer json = new JSONSerializer();
if ( item.description != null ) {
  json.exclude( field );
}
return json.serialize(item);

显然,您可能会使用 getter 访问描述字段。此外,您可能希望使用反射来迭代实例字段以排除空字段。

I haven't tried out your situation exactly, but I believe the following should solve your problem:

Item item;
// Assign item here
JSONSerializer json = new JSONSerializer();
if ( item.description != null ) {
  json.exclude( field );
}
return json.serialize(item);

Clearly, you'd probably access the description field using a getter. Additionally, you might want to iterate your instance fields using reflection to exclude the null-fields.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文