6

Flexjson を使用して、このようなクラスを JSON にシリアル化しています。

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

    // Getters and setters
    ...
}

アイテム フィールドの多くは null にすることができます (説明など)。したがって、このような Item オブジェクトを Flexjson を使用してシリアル化すると、次の JSON が得られます。

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

既に述べたように、Item オブジェクトには多くの null 値フィールドが含まれる可能性があるため、出力される JSON は実際に必要以上に長くなります。WiFi、3G、EDGE、または GPRS を介したワイヤレス接続を介して、生成された JSON を Web サーバーからモバイル クライアントに送信したいので、これはこれまでのところ問題です (つまり、より多くの帯域幅が必要であり、結果として速度が低下します)。 )。

したがって、Flexjson を使用して null 値の属性を (効率的に) 除外するにはどうすればよいでしょうか?

ありがとう!

4

3 に答える 3

18

次のトランスフォーマーを使用できます。

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)

null フィールドはすべて除外されることに注意してください。

FlexJSON は null 値に対して TypeTransformer を強制するため、パスによる (対クラスによる) Transformer の追加はサポートされていません。

JSONContext.java: 95行目:

private Transformer getPathTransformer(Object object) {
    if (null == object) return getTypeTransformer(object);
    return pathTransformerMap.get(path);
}
于 2012-04-16T12:57:05.700 に答える
1

私は初心者ですが、同じ問題があり、ソースフォージで解決策が見つからなかったため、正規表現を使用して JSON 文字列からすべての null を削除しました

/**
 * 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();
}
于 2012-09-21T12:16:04.933 に答える
-1

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.

于 2012-03-08T20:56:52.243 に答える