使用 Google 的 Gson 进行严格的 JSON 解析?

发布于 2024-09-07 21:49:54 字数 127 浏览 1 评论 0原文

假设我正在使用 Google 的 Gson 库将 JSON 解析为 Java 数据结构。

如果 Java 字段没有对应的 JSON,是否有简单的方法抛出异常?也就是说,我希望要求 JSON 具有 Java 结构中的所有字段。

Suppose I am using Google's Gson library to parse JSON into Java data structures.

Is there an easy way to throw an exception if there is a Java field that has no corresponding JSON? That is, I wish to require the JSON to have all the fields in the Java structure.

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

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

发布评论

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

评论(2

疯了 2024-09-14 21:49:55

Gson 没有 JSON 模式验证功能来指定必须存在特定元素,并且没有办法指定必须填充 Java 成员。拥有这样的功能可能会很好,例如使用 @Required 注释。前往Gson 问题列表并提出增强请求。

使用 Gson,您可以强制指定的 JSON 元素与自定义反序列化器一起出现。

// output: 
//   [MyObject: element1=value1, element2=value2, element3=value3]
//   [MyObject: element1=value1, element2=value2, element3=null]
//   Exception in thread "main" com.google.gson.JsonParseException: Required Field Not Found: element2

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class Foo
{
  static String jsonInput1 = "{\"element1\":\"value1\",\"element2\":\"value2\",\"element3\":\"value3\"}";
  static String jsonInput2 = "{\"element1\":\"value1\",\"element2\":\"value2\"}";
  static String jsonInput3 = "{\"element1\":\"value1\",\"element3\":\"value3\"}";

  public static void main(String[] args)
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    MyDeserializer deserializer = new MyDeserializer();
    deserializer.registerRequiredField("element2");
    gsonBuilder.registerTypeAdapter(MyObject.class, deserializer);
    Gson gson = gsonBuilder.create();
    MyObject object1 = gson.fromJson(jsonInput1, MyObject.class);
    System.out.println(object1);
    MyObject object2 = gson.fromJson(jsonInput2, MyObject.class);
    System.out.println(object2);
    MyObject object3 = gson.fromJson(jsonInput3, MyObject.class);
    System.out.println(object3);
  }
}

class MyObject
{
  String element1;
  String element2;
  String element3;

  @Override
  public String toString()
  {
    return String.format(
        "[MyObject: element1=%s, element2=%s, element3=%s]",
        element1, element2, element3);
  }
}

class MyDeserializer implements JsonDeserializer<MyObject>
{
  List<String> requiredFields = new ArrayList<String>();

  void registerRequiredField(String fieldName)
  {
    requiredFields.add(fieldName);
  }

  @Override
  public MyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException
  {
    JsonObject jsonObject = (JsonObject) json;
    for (String fieldName : requiredFields)
    {
      if (jsonObject.get(fieldName) == null)
      {
        throw new JsonParseException("Required Field Not Found: " + fieldName);
      }
    }
    return new Gson().fromJson(json, MyObject.class);
  }
}

更好的方法可能是使用提供 JSON 架构 验证的 API。 Jackson 至少有一个基本的实现JSON Tools 看起来有一个更成熟的工具。

这是杰克逊的一个例子。

// output: 
// Validating jsonInput1...
// Validating jsonInput2...
// Validating jsonInput3...
// $.element2: is missing and it is not optional
// [MyObject: element1=value1, element2=value2, element3=value3]
// [MyObject: element1=value1, element2=value2, element3=null]
// [MyObject: element1=value1, element2=null, element3=value3]

import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;

import eu.vahlas.json.schema.JSONSchema;
import eu.vahlas.json.schema.JSONSchemaProvider;
import eu.vahlas.json.schema.impl.JacksonSchemaProvider;

public class Foo
{
  static String jsonSchema = 
    "{" + 
        "\"description\":\"Serialized MyObject Specification\"," + 
        "\"type\":[\"object\"]," + 
        "\"properties\":" + 
        "{" + 
            "\"element1\":{\"type\":\"string\"}," + 
            "\"element2\":{\"type\":\"string\",\"optional\":false}," + 
            "\"element3\":{\"type\":\"string\",\"optional\":true}" + 
        "}" + 
    "}";;

  static String jsonInput1 = "{\"element1\":\"value1\",\"element2\":\"value2\",\"element3\":\"value3\"}";
  static String jsonInput2 = "{\"element1\":\"value1\",\"element2\":\"value2\"}";
  static String jsonInput3 = "{\"element1\":\"value1\",\"element3\":\"value3\"}";

  public static void main(String[] args) throws Exception
  {
    ObjectMapper mapper = new ObjectMapper();
    JSONSchemaProvider schemaProvider = new JacksonSchemaProvider(mapper);
    JSONSchema schema = schemaProvider.getSchema(jsonSchema);

    System.out.println("Validating jsonInput1...");
    validateAndLogErrors(jsonInput1, schema);
    System.out.println("Validating jsonInput2...");
    validateAndLogErrors(jsonInput2, schema);
    System.out.println("Validating jsonInput3...");
    validateAndLogErrors(jsonInput3, schema);

    MyObject object1 = mapper.readValue(jsonInput1, MyObject.class);
    System.out.println(object1);
    MyObject object2 = mapper.readValue(jsonInput2, MyObject.class);
    System.out.println(object2);
    MyObject object3 = mapper.readValue(jsonInput3, MyObject.class);
    System.out.println(object3);
  }

  static void validateAndLogErrors(String jsonInput, JSONSchema schema)
  {
    List<String> errors = schema.validate(jsonInput);
    for (String error : errors)
    {
      System.out.println(error);
    }
  }
}

class MyObject
{
  String element1;
  String element2;
  String element3;

  void setElement1(String element1)
  {
    this.element1 = element1;
  }

  void setElement2(String element2)
  {
    this.element2 = element2;
  }

  void setElement3(String element3)
  {
    this.element3 = element3;
  }

  @Override
  public String toString()
  {
    return String.format(
        "[MyObject: element1=%s, element2=%s, element3=%s]",
        element1, element2, element3);
  }
}

Gson doesn't have a JSON schema validation feature to specify that a particular element must be present, and it doesn't have a way to specify that a Java member must be populated. It might be nice to have such a feature available, such as with an @Required annotation. Head on over to the Gson Issues List and put in an enhancement request.

With Gson, you could enforce that specified JSON elements are present with a custom deserializer.

// output: 
//   [MyObject: element1=value1, element2=value2, element3=value3]
//   [MyObject: element1=value1, element2=value2, element3=null]
//   Exception in thread "main" com.google.gson.JsonParseException: Required Field Not Found: element2

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class Foo
{
  static String jsonInput1 = "{\"element1\":\"value1\",\"element2\":\"value2\",\"element3\":\"value3\"}";
  static String jsonInput2 = "{\"element1\":\"value1\",\"element2\":\"value2\"}";
  static String jsonInput3 = "{\"element1\":\"value1\",\"element3\":\"value3\"}";

  public static void main(String[] args)
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    MyDeserializer deserializer = new MyDeserializer();
    deserializer.registerRequiredField("element2");
    gsonBuilder.registerTypeAdapter(MyObject.class, deserializer);
    Gson gson = gsonBuilder.create();
    MyObject object1 = gson.fromJson(jsonInput1, MyObject.class);
    System.out.println(object1);
    MyObject object2 = gson.fromJson(jsonInput2, MyObject.class);
    System.out.println(object2);
    MyObject object3 = gson.fromJson(jsonInput3, MyObject.class);
    System.out.println(object3);
  }
}

class MyObject
{
  String element1;
  String element2;
  String element3;

  @Override
  public String toString()
  {
    return String.format(
        "[MyObject: element1=%s, element2=%s, element3=%s]",
        element1, element2, element3);
  }
}

class MyDeserializer implements JsonDeserializer<MyObject>
{
  List<String> requiredFields = new ArrayList<String>();

  void registerRequiredField(String fieldName)
  {
    requiredFields.add(fieldName);
  }

  @Override
  public MyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException
  {
    JsonObject jsonObject = (JsonObject) json;
    for (String fieldName : requiredFields)
    {
      if (jsonObject.get(fieldName) == null)
      {
        throw new JsonParseException("Required Field Not Found: " + fieldName);
      }
    }
    return new Gson().fromJson(json, MyObject.class);
  }
}

A preferable approach might be to use an API that provides JSON Schema validation. Jackson has at least a rudimentary implementation available. JSON Tools looks to have a more mature one.

Here's an example with Jackson.

// output: 
// Validating jsonInput1...
// Validating jsonInput2...
// Validating jsonInput3...
// $.element2: is missing and it is not optional
// [MyObject: element1=value1, element2=value2, element3=value3]
// [MyObject: element1=value1, element2=value2, element3=null]
// [MyObject: element1=value1, element2=null, element3=value3]

import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;

import eu.vahlas.json.schema.JSONSchema;
import eu.vahlas.json.schema.JSONSchemaProvider;
import eu.vahlas.json.schema.impl.JacksonSchemaProvider;

public class Foo
{
  static String jsonSchema = 
    "{" + 
        "\"description\":\"Serialized MyObject Specification\"," + 
        "\"type\":[\"object\"]," + 
        "\"properties\":" + 
        "{" + 
            "\"element1\":{\"type\":\"string\"}," + 
            "\"element2\":{\"type\":\"string\",\"optional\":false}," + 
            "\"element3\":{\"type\":\"string\",\"optional\":true}" + 
        "}" + 
    "}";;

  static String jsonInput1 = "{\"element1\":\"value1\",\"element2\":\"value2\",\"element3\":\"value3\"}";
  static String jsonInput2 = "{\"element1\":\"value1\",\"element2\":\"value2\"}";
  static String jsonInput3 = "{\"element1\":\"value1\",\"element3\":\"value3\"}";

  public static void main(String[] args) throws Exception
  {
    ObjectMapper mapper = new ObjectMapper();
    JSONSchemaProvider schemaProvider = new JacksonSchemaProvider(mapper);
    JSONSchema schema = schemaProvider.getSchema(jsonSchema);

    System.out.println("Validating jsonInput1...");
    validateAndLogErrors(jsonInput1, schema);
    System.out.println("Validating jsonInput2...");
    validateAndLogErrors(jsonInput2, schema);
    System.out.println("Validating jsonInput3...");
    validateAndLogErrors(jsonInput3, schema);

    MyObject object1 = mapper.readValue(jsonInput1, MyObject.class);
    System.out.println(object1);
    MyObject object2 = mapper.readValue(jsonInput2, MyObject.class);
    System.out.println(object2);
    MyObject object3 = mapper.readValue(jsonInput3, MyObject.class);
    System.out.println(object3);
  }

  static void validateAndLogErrors(String jsonInput, JSONSchema schema)
  {
    List<String> errors = schema.validate(jsonInput);
    for (String error : errors)
    {
      System.out.println(error);
    }
  }
}

class MyObject
{
  String element1;
  String element2;
  String element3;

  void setElement1(String element1)
  {
    this.element1 = element1;
  }

  void setElement2(String element2)
  {
    this.element2 = element2;
  }

  void setElement3(String element3)
  {
    this.element3 = element3;
  }

  @Override
  public String toString()
  {
    return String.format(
        "[MyObject: element1=%s, element2=%s, element3=%s]",
        element1, element2, element3);
  }
}
装纯掩盖桑 2024-09-14 21:49:55

您可以递归地验证 json 是否包含类中未声明的字段:

 private static List<String> verifyElement(JsonObject element, Class klass) throws NoSuchFieldException, IllegalAccessException {
  List<String> unknownFields = new ArrayList<>();
  Set<String> classFields = new HashSet<>();

  for (Field field : klass.getDeclaredFields()) {
    if (!Modifier.isPublic(field.getModifiers())) {
      throw new IllegalArgumentException("All fields must be public. Please correct this field :" + field);
    }
  }

  for (Field field : klass.getFields()) {
    classFields.add(field.getName());
  }

  // Verify recursively that the class contains every
  for (Map.Entry<String, JsonElement> entry : element.entrySet()) {
    if (!classFields.contains(entry.getKey())) {
      unknownFields.add(klass.getCanonicalName() + "::" + entry.getKey() + "\n");
    } else {
      Field field = klass.getField(entry.getKey());
      Class fieldClass = field.getType();
      if (!fieldClass.isPrimitive() && entry.getValue().isJsonObject()) {
        List<String> elementErrors = verifyElement(entry.getValue().getAsJsonObject(), fieldClass);
        unknownFields.addAll(elementErrors);
      }
    }
  }
  return unknownFields;

}

You can recursively verify whether the json contains fields that are not declared in the class :

 private static List<String> verifyElement(JsonObject element, Class klass) throws NoSuchFieldException, IllegalAccessException {
  List<String> unknownFields = new ArrayList<>();
  Set<String> classFields = new HashSet<>();

  for (Field field : klass.getDeclaredFields()) {
    if (!Modifier.isPublic(field.getModifiers())) {
      throw new IllegalArgumentException("All fields must be public. Please correct this field :" + field);
    }
  }

  for (Field field : klass.getFields()) {
    classFields.add(field.getName());
  }

  // Verify recursively that the class contains every
  for (Map.Entry<String, JsonElement> entry : element.entrySet()) {
    if (!classFields.contains(entry.getKey())) {
      unknownFields.add(klass.getCanonicalName() + "::" + entry.getKey() + "\n");
    } else {
      Field field = klass.getField(entry.getKey());
      Class fieldClass = field.getType();
      if (!fieldClass.isPrimitive() && entry.getValue().isJsonObject()) {
        List<String> elementErrors = verifyElement(entry.getValue().getAsJsonObject(), fieldClass);
        unknownFields.addAll(elementErrors);
      }
    }
  }
  return unknownFields;

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