flexjson.JSONSerializer类的使用及代码示例

x33g5p2x  于2022-01-22 转载在 其他  
字(14.5k)|赞(0)|评价(0)|浏览(120)

本文整理了Java中flexjson.JSONSerializer类的一些代码示例,展示了JSONSerializer类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JSONSerializer类的具体详情如下:
包路径:flexjson.JSONSerializer
类名称:JSONSerializer

JSONSerializer介绍

[英]JSONSerializer is the main class for performing serialization of Java objects to JSON. JSONSerializer by default performs a shallow serialization. While this might seem strange there is a method to this madness. Shallow serialization allows the developer to control what is serialized out of the object graph. This helps with performance, but more importantly makes good OO possible, fixes the circular reference problem, and doesn't require boiler plate translation code. You don't have to change your object model to make JSON work so it reduces your work load, and keeps you DRY.

Let's go through a simple example:

JSONSerializer serializer = new JSONSerializer(); 
return serializer.serialize( person );

What this statement does is output the json from the instance of person. So the JSON we might see for this could look like:

{ "class": "com.mysite.Person", 
"firstname": "Charlie", 
"lastname": "Rose", 
"age", 23 
"birthplace": "Big Sky, Montanna" 
}

In this case it's look like it's pretty standard stuff. But, let's say Person had many hobbies (i.e. Person.hobbies is a java.util.List). In this case if we executed the code above we'd still getTransformer the same output. This is a very important feature of flexjson, and that is any instance variable that is a Collection, Map, or Object reference won't be serialized by default. This is what gives flexjson the shallow serialization.

How would we include the hobbies field? Using the JSONSerializer#includemethod allows us to include these fields in the serialization process. Here is how we'd do that:

return new JSONSerializer().include("hobbies").serialize( person );

That would produce output like:

{ "class": "com.mysite.Person", 
"firstname": "Charlie", 
"lastname": "Rose", 
"age", 23 
"birthplace": "Big Sky, Montanna", 
"hobbies", [ 
"poker", 
"snowboarding", 
"kite surfing", 
"bull riding" 
] 
}

If the hobbies field contained objects, say Hobby instances, then a shallow copy of those objects would be performed. Let's go further and say hobbies had a List of all the people who enjoyed this hobby. This would create a circular reference between Person and Hobby. Since the shallow copy is being performed on Hobby JSONSerialize won't serialize the people field when serializing Hobby instances thus breaking the chain of circular references.

But, for the sake of argument and illustration let's say we wanted to send the people field in Hobby. We can do the following:

return new JSONSerializer().include("hobbies.people").serialize( person );

JSONSerializer is smart enough to know that you want hobbies field included and the people field inside hobbies' instances too. The dot notation allows you do traverse the object graph specifying instance fields. But, remember a shallow copy will stop the code from getting into an infinte loop.

You can also use the exclude method to exclude fields that would be included. Say we have a User object. It would be a serious security risk if we sent the password over the network. We can use the exclude method to prevent the password field from being sent.

return new JSONSerialize().exclude("password").serialize(user);

JSONSerializer will also pay attention to any method or field annotated by flexjson.JSON. You can include and exclude fields permenantly using the annotation. This is good like in the case of User.password which should never ever be sent through JSON. However, fields like hobbies or favoriteMovies depends on the situation so it's best NOT to annotate those fields, and use the JSONSerializer#include method.

In a shallow copy only these types of instance fields will be sent: String, Date, Number, Boolean, Character, Enum, Object and null. Subclasses of Object will be serialized except for Collection or Arrays. Anything that would cause a N objects would not be sent. All types will be excluded by default. Fields marked static or transient are not serialized.

Includes and excludes can include wildcards. Wildcards allow you to do things like exclude all class attributes. For example *.class would remove the class attribute that all objects have when serializing. A open ended wildcard like * would cause deep serialization to take place. Be careful with that one. Although you can limit it's depth with an exclude like *.foo. The order of evaluation of includes and excludes is the order in which you called their functions. First call to those functions will cause those expressions to be evaluated first. The first expression to match a path that action will be taken thus short circuiting all other expressions defined later.

Transforers are a new addition that allow you to modify the values that are being serialized. This allows you to create different output for certain conditions. This is very important in web applications. Say you are saving your text to the DB that could contain < and >. If you plan to add that content to your HTML page you'll need to escape those characters. Transformers allow you to do this. Flexjson ships with a simple HTML encoder flexjson.transformer.HtmlEncoderTransformer. Transformers are specified in dot notation just like include and exclude methods, but it doesn't support wildcards.

JSONSerializer is safe to use the serialize() methods from two seperate threads. It is NOT safe to use combination of JSONSerializer#include(String...)JSONSerializer#transform(flexjson.transformer.Transformer,String...), or JSONSerializer#exclude(String...)from multiple threads at the same time. It is also NOT safe to use JSONSerializer#serialize(Object) and include/exclude/transform from multiple threads. The reason for not making them more thread safe is to boost performance. Typical use case won't call for two threads to modify the JsonSerializer at the same type it's trying to serialize.
[中]JSONSerializer是将Java对象序列化为JSON的主要类。默认情况下,JSONSerializer执行浅层序列化。虽然这看起来很奇怪,但有一种方法可以解决这种疯狂。浅层序列化允许开发人员控制从对象图中序列化的内容。这有助于提高性能,但更重要的是使良好的OO成为可能,修复了循环引用问题,并且不需要锅炉板翻译代码。您不必更改对象模型以使JSON正常工作,从而减少您的工作负载,并使您保持DRY
让我们看一个简单的例子:

JSONSerializer serializer = new JSONSerializer(); 
return serializer.serialize( person );

此语句所做的是从person实例输出json。因此,我们看到的JSON可能如下所示:

{ "class": "com.mysite.Person", 
"firstname": "Charlie", 
"lastname": "Rose", 
"age", 23 
"birthplace": "Big Sky, Montanna" 
}

在这种情况下,它看起来是相当标准的东西。但是,假设Person有很多爱好(即Person.cabiods是java.util.List)。在这种情况下,如果我们执行上面的代码,我们仍然会得到相同的输出。这是flexjson的一个非常重要的特性,默认情况下,任何作为集合、映射或对象引用的实例变量都不会序列化。这就是flexjson的浅层序列化的原因。
我们如何将“爱好”字段包括在内?使用JSONSerializer#includemethod可以在序列化过程中包含这些字段。下面是我们将如何做到这一点:

return new JSONSerializer().include("hobbies").serialize( person );

这将产生如下产出:

{ "class": "com.mysite.Person", 
"firstname": "Charlie", 
"lastname": "Rose", 
"age", 23 
"birthplace": "Big Sky, Montanna", 
"hobbies", [ 
"poker", 
"snowboarding", 
"kite surfing", 
"bull riding" 
] 
}

如果嗜好字段包含对象,例如嗜好实例,则将执行这些对象的浅层复制。让我们更进一步,说“嗜好”有一份所有喜欢这个嗜好的人的名单。这将在人和爱好之间创建一个循环引用。由于浅层复制是在Hobby上执行的,所以序列化Hobby实例时,JSONSerialize不会序列化people字段,从而打破循环引用链。
但是,为了论证和说明,让我们假设我们想把“人”这个领域列入业余爱好。我们可以做到以下几点:

return new JSONSerializer().include("hobbies.people").serialize( person );

JSONSerializer足够聪明,知道您想要包含嗜好字段,以及嗜好实例中的人员字段。点表示法允许您通过指定实例字段遍历对象图。但是,请记住,浅拷贝将阻止代码进入infinte循环。
您还可以使用exclude方法排除要包括的字段。假设我们有一个用户对象。如果我们通过网络发送密码,这将是一个严重的安全风险。我们可以使用exclude方法阻止发送密码字段。

return new JSONSerialize().exclude("password").serialize(user);

JSONSerializer还将关注flexjson注释的任何方法或字段。JSON。可以使用注释永久包含和排除字段。这与用户的情况类似。永远不应该通过JSON发送的密码。但是,像嗜好favoriteMovies这样的字段取决于具体情况,因此最好不要对这些字段进行注释,而是使用JSONSerializer#include方法。
在浅表副本中,只发送以下类型的实例字段:字符串、日期、数字、布尔值、字符、枚举、对象和null。对象的子类将被序列化,集合或数组除外。任何会导致N个对象丢失的内容都不会被发送。默认情况下,将排除所有类型。标记为静态或瞬态的字段不会序列化。
包括和排除可以包括通配符。通配符允许您执行排除所有类属性之类的操作。例如*。类将删除序列化时所有对象都具有的类属性。像这样的开放式通配符将导致深度序列化。小心那个。尽管可以使用类似的排除来限制其深度。福。include和excludes的求值顺序是调用其函数的顺序。对这些函数的第一次调用将导致首先计算这些表达式。匹配将执行操作的路径的第一个表达式,从而使后面定义的所有其他表达式短路。
Transforer是一个新的添加项,允许您修改正在序列化的值。这允许您针对特定条件创建不同的输出。这在web应用程序中非常重要。假设您正在将文本保存到可能包含<和>的数据库中。如果您计划将该内容添加到HTML页面,则需要转义这些字符。变形金刚允许你这样做。Flexjson附带了一个简单的HTML编码器Flexjson。变压器HtmlEncoderTransformer。与include和exclude方法一样,transformer是用点表示法指定的,但它不支持通配符。
JSONSerializer可以安全地使用来自两个独立线程的serialize()方法。使用JSONSerializer#include(String…)的组合是不安全的JSONSerializer#transform(flexjson.transformer.transformer,String…),或JSONSerializer#排除(字符串…)同时从多个线程执行。使用JSONSerializer#序列化(对象)并从多个线程中包含/排除/转换也是不安全的。不让它们更线程安全的原因是为了提高性能。典型的用例不会要求两个线程在试图序列化的同一类型上修改JsonSerializer。

代码示例

代码示例来源:origin: spring-projects/spring-integration-samples

public String toJson() {
  return new JSONSerializer().exclude("*.class").serialize(this);
}

代码示例来源:origin: Medisana/vitadock-api

/**
 * Method toJsonArray.
 * @param collection Collection<TrackerSleep>
 * @return String
 */
public static final String toJsonArray(
    final Collection<TrackerSleep> collection) {
  return new JSONSerializer().include("trackerSleepQualities").exclude("*.class")
      .exclude("active").exclude("updatedDate").exclude("version")
      .exclude("uuid").serialize(collection);
}

代码示例来源:origin: dragome/dragome-sdk

/**
 * This performs a shallow serialization of the target instance and
 * passes the generated JSON into the provided OutputHandler.
 *
 * @param target - the instance to serialize to JSON
 * @param out - OutputHandler to write output to
 * @return returns JSON as a String
 */
public String serialize(Object target, OutputHandler out)
{
  return serialize(target, SerializationType.SHALLOW, out);
}

代码示例来源:origin: pentaho/marketplace

protected String encodeToJSON() {
 JSONSerializer serializer = new JSONSerializer();
 return serializer.deepSerialize( this );
}

代码示例来源:origin: pentaho/data-access

@Override
public void writeTo( IDatabaseConnectionList t, Class<?> type, Type genericType, Annotation[] annotations,
           MediaType mediaType,
           MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream )
 throws IOException, WebApplicationException {
 OutputStreamWriter outputStreamWriter = new OutputStreamWriter( entityStream );
 try {
  new JSONSerializer().exclude( "*.class" ).deepSerialize( t, outputStreamWriter );
 } finally {
  outputStreamWriter.close();
 }
}

代码示例来源:origin: org.motechproject/motech-server-core

@Override
public String toString() {
  return new JSONSerializer().serialize(this);
}

代码示例来源:origin: dragome/dragome-sdk

private JSONSerializer createSerializer()
{
  jsonSerializer= new JSONSerializer();
  jsonSerializer.transform(new ElementTrasformer(), Element.class);
  jsonSerializer.transform(new MethodTrasformer(), Method.class);
  jsonSerializer.transform(new DragomeClassTransformer(), Class.class);
  return jsonSerializer;
}

代码示例来源:origin: magro/memcached-session-manager

/**
 * Constructor
 * @param manager
 */
public JSONTranscoder(final Manager manager) {
  serializer = new JSONSerializer();
  deserializer = new JSONDeserializer<ConcurrentMap<String, Object>>();
  if (LOG.isDebugEnabled()) {
    LOG.debug("Initialized json serializer");
  }
}

代码示例来源:origin: fabienrenaud/java-json-benchmark

@Benchmark
@Override
public Object flexjson() {
  StringBuilder b = JsonUtils.stringBuilder();
  JSON_SOURCE().provider().flexjsonSer().exclude("*.class").deepSerialize(JSON_SOURCE().nextPojo(), b);
  return b;
}

代码示例来源:origin: magro/memcached-session-manager

@Override
public byte[] serializeAttributes(final MemcachedBackupSession sessions, final ConcurrentMap<String, Object> attributes) {
  if (attributes == null) {
    throw new NullPointerException();
  }
  final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try {
    // This performs a deep serialization of the target instance.
    // It's serialized to a string as flexjson doesn't like writing to
    // an OutputStreamWriter: it throws the exception "Stepping back two steps is not supported".
    // See https://github.com/moresandeep/memcached-session-manager/commit/db2faaa0a846e16d65ac0b14819689c67bf92c68#commitcomment-512505
    final String serResult = serializer.deepSerialize(attributes);
    if (LOG.isDebugEnabled()) {
      LOG.debug("JSON Serialised object: " + serResult);
    }
    return serResult.getBytes(); // converts to bytes
  } catch (final Exception e) {
    LOG.warn("Caught Exception deserializing JSON " + e);
    throw new IllegalArgumentException();
  } finally {
    close(bos);
  }
}

代码示例来源:origin: dragome/dragome-sdk

public void addTransformer(Transformer transformer, Class<?>... types)
{
  jsonSerializer.transform(transformer, types);
}

代码示例来源:origin: Medisana/vitadock-api

/**
 * Method toJsonArray.
 * @param collection Collection<Activitydock>
 * @return String
 */
public static final String toJsonArray(final Collection<Activitydock> collection) {
  return new JSONSerializer().include("activities", "distances")
      .exclude("*.class").exclude("active").exclude("updatedDate")
      .exclude("version").exclude("id").serialize(collection);
}

代码示例来源:origin: dragome/dragome-sdk

/**
 * This performs a deep serialization of the target instance and
 * passes the generated JSON into the provided OutputHandler.
 *
 * @param target - the instance to serialize to JSON
 * @param out - OutputHandler to write to
 * @return returns JSON as a String
 */
public String deepSerialize(Object target, OutputHandler out)
{
  return serialize(target, SerializationType.DEEP, out);
}

代码示例来源:origin: pentaho/data-access

/**
 * Returns a JSON list of the available business models
 *
 * @param domainName optional domain to limit the results
 * @return JSON string of list of ModelInfo objects representing the available models
 * @throws IOException
 */
public String listBusinessModelsJson( String domainName ) throws IOException {
 ModelInfo[] models = listBusinessModels( domainName );
 JSONSerializer serializer = new JSONSerializer();
 String json = serializer.deepSerialize( models );
 return json;
}

代码示例来源:origin: pentaho/data-access

@Override
public void writeTo( IDatabaseTypesList t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
           MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream ) throws IOException, WebApplicationException {
 OutputStreamWriter outputStreamWriter = new OutputStreamWriter( entityStream );
 try {
  new JSONSerializer().exclude( "*.class" ).deepSerialize( t, outputStreamWriter );
 } finally {
  outputStreamWriter.close();
 }
}

代码示例来源:origin: groupon/odo

query.setString(1, String.valueOf(overrideId));
results = query.executeQuery();
JSONSerializer serializer = new JSONSerializer();
if (results.next()) {
  String className = results.getString(Constants.OVERRIDE_CLASS_NAME);
  statement.setString(6, serializer.serialize(argDefaults));

代码示例来源:origin: com.googlecode.mycontainer/mycontainer-commons

public JsonHandler() {
  this.serializer = new JSONSerializer();
  deserializer = new JSONDeserializer<Object>();
  serializer.transform(new CharacterTransformer(), CharSequence.class);
  serializer.transform(new IterableTransformer(), List.class);
  serializer.transform(new MapTransformer(), Map.class);
}

代码示例来源:origin: fabienrenaud/java-json-benchmark

@Override
  protected JSONSerializer initialValue() {
    return new JSONSerializer();
  }
};

代码示例来源:origin: dragome/dragome-sdk

public String serialize(Object object)
{
  return jsonSerializer.deepSerialize(object);
}

代码示例来源:origin: forcelate/forcelate-benchmarks

@PostConstruct
public void init() {
  serializer.transform(DF, Date.class);
}

相关文章