2013-06-11 33 views
13

Tôi có bộ giải mã netty sử dụng GSon để chuyển đổi JSon từ máy khách web sang các đối tượng java thích hợp. Yêu cầu là: Khách hàng có thể gửi các lớp không liên quan, Class A, Class B, Class C vv nhưng tôi muốn sử dụng cùng singleton decoder instance trong đường dẫn để thực hiện chuyển đổi (vì tôi sử dụng spring để cấu hình nó) . Vấn đề tôi đang phải đối mặt là tôi cần phải biết đối tượng class trước khi bàn tay.Chuyển đổi từ JSon sang nhiều loại đối tượng java không xác định bằng cách sử dụng GSon

public Object decode() 
{ 
    gson.fromJson(jsonString, A.class); 
} 

Điều này không thể giải mã B hoặc C. Người dùng thư viện của tôi, bây giờ cần phải viết bộ giải mã riêng cho từng lớp thay vì truyền sau. Cách duy nhất tôi có thể thấy để làm điều này là truyền tên String của lớp nói "org.example.C" trong chuỗi JSon từ trình khách web, phân tích cú pháp nó trong bộ giải mã và sau đó sử dụng Class.forName để lấy lớp. Có cách nào tốt hơn để làm điều này?

+2

Nếu đây là một thành phần có mục đích chung, hãy nghĩ về cách bạn muốn người dùng định cấu hình nó. Mặc định hợp lý cũng đáng để suy nghĩ. Nó sẽ có ý nghĩa để có nhiều trường hợp bộ giải mã, một trong mỗi lớp học? – Jukka

+0

Thats làm thế nào tôi làm điều này hiện nay, một ví dụ cho mỗi loại lớp. Vấn đề là người dùng thư viện của tôi bây giờ cần phải thực hiện các chi tiết nội bộ như bộ giải mã và bộ mã hóa và định cấu hình chúng vào mùa xuân mỗi khi một lớp mới được thêm vào. Tôi muốn tha cho họ và thay vào đó làm một dàn diễn viên đơn giản. – Abe

Trả lời

10

GSon PHẢI biết lớp khớp với chuỗi json. Nếu bạn không wan't để cung cấp nó với fromJson(), bạn thực sự có thể xác định nó trong Json. Một cách là để xác định một giao diện và ràng buộc một bộ điều hợp trên nó.

Giống như:

class A implements MyInterface { 
    // ... 
    } 

    public Object decode() 
    { 
    Gson gson = builder.registerTypeAdapter(MyInterface.class, new MyInterfaceAdapter()); 
    MyInterface a = gson.fromJson(jsonString, MyInterface.class); 
    } 

Adaptor có thể như:

public final class MYInterfaceAdapter implements JsonDeserializer<MyInterface>, JsonSerializer<MyInterface> { 
    private static final String PROP_NAME = "myClass"; 

    @Override 
    public MyInterface deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
    try { 
     String classPath = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString(); 
     Class<MyInterface> cls = (Class<MyInterface>) Class.forName(classPath); 

     return (MyInterface) context.deserialize(json, cls); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 

    return null; 
    } 

    @Override 
    public JsonElement serialize(MyInterface src, Type typeOfSrc, JsonSerializationContext context) { 
    // note : won't work, you must delegate this 
    JsonObject jo = context.serialize(src).getAsJsonObject(); 

    String classPath = src.getClass().getName(); 
    jo.add(PROP_NAME, new JsonPrimitive(classPath)); 

    return jo; 
    } 
} 
+0

Vấn đề ở đây là lớp B sẽ không triển khai 'MyInterface'. Đây không phải là các lớp được liên kết hợp lý. Nhưng có lẽ tôi cần phải làm cho người dùng của lib thực hiện một giao diện đánh dấu để làm cho mã này hoạt động. – Abe

+0

Vì vậy, tôi sẽ đi với một TypeAdapterFactory. Điểm chính là JSon phải cung cấp lớp để khởi tạo. GSon không phải là phép thuật, nó không thể đoán cho bạn :) – PomPom

+0

Vì 1.7 'GsonBuilder' builder có [registerTypeHierarchyAdapter] (https://google.github.io/gson/apidocs/com/google/gson/GsonBuilder.html# registerTypeHierarchyAdapter-java.lang.Class-java.lang.Object-) phương pháp có thể phù hợp hơn trong trường hợp này. Xem [thảo luận] (https://groups.google.com/forum/#!topic/google-gson/0ebOxifqwb0). – Vadzim

5

Giả sử bạn có những 2 phản ứng JSON có thể:

{ 
    "classA": {"foo": "fooValue"} 
} 
    or 
{ 
    "classB": {"bar": "barValue"} 
} 

Bạn có thể tạo một cấu trúc lớp như thế này:

public class Response { 
    private A classA; 
    private B classB; 
    //more possible responses... 
    //getters and setters... 
} 

public class A { 
    private String foo; 
    //getters and setters... 
} 

public class B { 
    private String bar; 
    //getters and setters... 
} 

Sau đó, bạn có thể phân tích bất kỳ phản hồi JSON có thể với:

Response response = gson.fromJson(jsonString, Response.class); 

Gson sẽ bỏ qua tất cả các trường JSON không tương ứng với bất kỳ thuộc tính nào trong cấu trúc lớp học của bạn, vì vậy bạn có thể thích ứng một lớp duy nhất để phân tích phản ứng khác nhau ...

Sau đó, bạn có thể kiểm tra các thuộc tính classA, classB ... không phải là null và bạn sẽ biết được câu trả lời bạn nhận được .

+0

Đây là thư viện được xuất bản cho người dùng -> https://github.com/menacher/java-game-server nên tôi thực sự không biết lớp học của mình. Vì vậy, không có cách nào mà tôi có thể điền vào lớp Response. – Abe

+1

@ Vâng, vì vậy bạn phải phân tích cú pháp một số câu trả lời JSON và bạn không biết cách họ xem xét tất cả? Đây thực sự là công việc khó khăn! – MikO

+0

Trên thực tế, khách hàng có thể gửi tên lớp vì họ biết họ đang gửi gì, vì vậy nó không phải là nguyên nhân bị mất. – Abe

1

Tạo mô hình lớp,

public class MyModel { 

    private String errorId; 

    public String getErrorId() { 
     return errorId; 
    } 

    public void setErrorId(String errorId) { 
     this.errorId = errorId; 
    } 
} 

Tạo lớp con

public class SubClass extends MyModel { 
     private String subString; 

     public String getSubString() { 
      return subString; 
     } 

     public void setSubString(String subString) { 
      this.subString = subString; 
     } 
} 

gọi parseGson Phương pháp

parseGson(subClass); 

phương pháp gson phân tích cú pháp với lớp đối tượng

public void parseGson(Object object){ 
    object = gson.fromJson(response.toString(), object.getClass()); 
    SubClass subclass = (SubClass)object; 
    } 

Bạn có thể thiết lập các biến toàn cầu đúc để MyModel

((MyModel)object).setErrorId(response.getString("errorid")); 
3

Không chắc chắn nếu điều này là những gì bạn đã yêu cầu , nhưng bằng cách sửa đổi lớp RuntimeTypeAdapterFactory, tôi đã tạo một hệ thống cho phân lớp dựa trên các điều kiện trong nguồn Json. RuntimeTypeAdapterFactory.class:

/* 
* Copyright (C) 2011 Google Inc. 
* 
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
*  http://www.apache.org/licenses/LICENSE-2.0 
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed under the License is distributed on an "AS IS" BASIS, 
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License. 
*/ 

package com.google.gson.typeadapters; 

import java.io.IOException; 
import java.util.LinkedHashMap; 
import java.util.Map; 

import com.google.gson.Gson; 
import com.google.gson.JsonElement; 
import com.google.gson.JsonObject; 
import com.google.gson.JsonParseException; 
import com.google.gson.JsonPrimitive; 
import com.google.gson.TypeAdapter; 
import com.google.gson.TypeAdapterFactory; 
import com.google.gson.internal.Streams; 
import com.google.gson.reflect.TypeToken; 
import com.google.gson.stream.JsonReader; 
import com.google.gson.stream.JsonWriter; 

/** 
* Adapts values whose runtime type may differ from their declaration type. This 
* is necessary when a field's type is not the same type that GSON should create 
* when deserializing that field. For example, consider these types: 
* <pre> {@code 
* abstract class Shape { 
*  int x; 
*  int y; 
* } 
* class Circle extends Shape { 
*  int radius; 
* } 
* class Rectangle extends Shape { 
*  int width; 
*  int height; 
* } 
* class Diamond extends Shape { 
*  int width; 
*  int height; 
* } 
* class Drawing { 
*  Shape bottomShape; 
*  Shape topShape; 
* } 
* }</pre> 
* <p>Without additional type information, the serialized JSON is ambiguous. Is 
* the bottom shape in this drawing a rectangle or a diamond? <pre> {@code 
* { 
*  "bottomShape": { 
*  "width": 10, 
*  "height": 5, 
*  "x": 0, 
*  "y": 0 
*  }, 
*  "topShape": { 
*  "radius": 2, 
*  "x": 4, 
*  "y": 1 
*  } 
* }}</pre> 
* This class addresses this problem by adding type information to the 
* serialized JSON and honoring that type information when the JSON is 
* deserialized: <pre> {@code 
* { 
*  "bottomShape": { 
*  "type": "Diamond", 
*  "width": 10, 
*  "height": 5, 
*  "x": 0, 
*  "y": 0 
*  }, 
*  "topShape": { 
*  "type": "Circle", 
*  "radius": 2, 
*  "x": 4, 
*  "y": 1 
*  } 
* }}</pre> 
* Both the type field name ({@code "type"}) and the type labels ({@code 
* "Rectangle"}) are configurable. 
* 
* <h3>Registering Types</h3> 
* Create a {@code RuntimeTypeAdapter} by passing the base type and type field 
* name to the {@link #of} factory method. If you don't supply an explicit type 
* field name, {@code "type"} will be used. <pre> {@code 
* RuntimeTypeAdapter<Shape> shapeAdapter 
*  = RuntimeTypeAdapter.of(Shape.class, "type"); 
* }</pre> 
* Next register all of your subtypes. Every subtype must be explicitly 
* registered. This protects your application from injection attacks. If you 
* don't supply an explicit type label, the type's simple name will be used. 
* <pre> {@code 
* shapeAdapter.registerSubtype(Rectangle.class, "Rectangle"); 
* shapeAdapter.registerSubtype(Circle.class, "Circle"); 
* shapeAdapter.registerSubtype(Diamond.class, "Diamond"); 
* }</pre> 
* Finally, register the type adapter in your application's GSON builder: 
* <pre> {@code 
* Gson gson = new GsonBuilder() 
*  .registerTypeAdapter(Shape.class, shapeAdapter) 
*  .create(); 
* }</pre> 
* Like {@code GsonBuilder}, this API supports chaining: <pre> {@code 
* RuntimeTypeAdapter<Shape> shapeAdapter = RuntimeTypeAdapterFactory.of(Shape.class) 
*  .registerSubtype(Rectangle.class) 
*  .registerSubtype(Circle.class) 
*  .registerSubtype(Diamond.class); 
* }</pre> 
*/ 
public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory { 
    private final Class<?> baseType; 
    private final RuntimeTypeAdapterPredicate predicate; 
    private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<String, Class<?>>(); 
    private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<Class<?>, String>(); 

    private RuntimeTypeAdapterFactory(Class<?> baseType, RuntimeTypeAdapterPredicate predicate) { 
     if (predicate == null || baseType == null) { 
      throw new NullPointerException(); 
     } 
     this.baseType = baseType; 
     this.predicate = predicate; 
    } 

    /** 
    * Creates a new runtime type adapter using for {@code baseType} using {@code 
    * typeFieldName} as the type field name. Type field names are case sensitive. 
    */ 
    public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, RuntimeTypeAdapterPredicate predicate) { 
     return new RuntimeTypeAdapterFactory<T>(baseType, predicate); 
    } 

    /** 
    * Creates a new runtime type adapter for {@code baseType} using {@code "type"} as 
    * the type field name. 
    */ 
    public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) { 
     return new RuntimeTypeAdapterFactory<T>(baseType, null); 
    } 

    /** 
    * Registers {@code type} identified by {@code label}. Labels are case 
    * sensitive. 
    * 
    * @throws IllegalArgumentException if either {@code type} or {@code label} 
    *  have already been registered on this type adapter. 
    */ 
    public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) { 
     if (type == null || label == null) { 
      throw new NullPointerException(); 
     } 
     if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) { 
      throw new IllegalArgumentException("types and labels must be unique"); 
     } 
     labelToSubtype.put(label, type); 
     subtypeToLabel.put(type, label); 
     return this; 
    } 

    /** 
    * Registers {@code type} identified by its {@link Class#getSimpleName simple 
    * name}. Labels are case sensitive. 
    * 
    * @throws IllegalArgumentException if either {@code type} or its simple name 
    *  have already been registered on this type adapter. 
    */ 
    public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) { 
     return registerSubtype(type, type.getSimpleName()); 
    } 

    public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { 
     if (type.getRawType() != baseType) { 
      return null; 
     } 

     final Map<String, TypeAdapter<?>> labelToDelegate 
       = new LinkedHashMap<String, TypeAdapter<?>>(); 
     final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate 
       = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); 
     for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { 
      TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); 
      labelToDelegate.put(entry.getKey(), delegate); 
      subtypeToDelegate.put(entry.getValue(), delegate); 
     } 

     return new TypeAdapter<R>() { 
      @Override public R read(JsonReader in) throws IOException { 
       JsonElement jsonElement = Streams.parse(in); 
       String label = predicate.process(jsonElement); 
       @SuppressWarnings("unchecked") // registration requires that subtype extends T 
         TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); 
       if (delegate == null) { 
        throw new JsonParseException("cannot deserialize " + baseType + " subtype named " 
          + label + "; did you forget to register a subtype?"); 
       } 
       return delegate.fromJsonTree(jsonElement); 
      } 

      @Override public void write(JsonWriter out, R value) throws IOException { // Unimplemented as we don't use write. 
       /*Class<?> srcType = value.getClass(); 
       String label = subtypeToLabel.get(srcType); 
       @SuppressWarnings("unchecked") // registration requires that subtype extends T 
         TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); 
       if (delegate == null) { 
        throw new JsonParseException("cannot serialize " + srcType.getName() 
          + "; did you forget to register a subtype?"); 
       } 
       JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); 
       if (jsonObject.has(typeFieldName)) { 
        throw new JsonParseException("cannot serialize " + srcType.getName() 
          + " because it already defines a field named " + typeFieldName); 
       } 
       JsonObject clone = new JsonObject(); 
       clone.add(typeFieldName, new JsonPrimitive(label)); 
       for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { 
        clone.add(e.getKey(), e.getValue()); 
       }*/ 
       Streams.write(null, out); 
      } 
     }; 
    } 
} 

RuntimeTypeAdapterPredicate.class:

package com.google.gson.typeadapters; 

import com.google.gson.JsonElement; 

/** 
* Created by Johan on 2014-02-13. 
*/ 
public abstract class RuntimeTypeAdapterPredicate { 

    public abstract String process(JsonElement element); 

} 

Ví dụ (lấy từ một dự án tôi hiện đang làm việc trên):

ItemTypePredicate.class:

package org.libpoe.serial; 

import com.google.gson.JsonElement; 
import com.google.gson.JsonObject; 
import com.google.gson.typeadapters.RuntimeTypeAdapterPredicate; 

/** 
* Created by Johan on 2014-02-13. 
*/ 
public class ItemTypePredicate extends RuntimeTypeAdapterPredicate { 

    @Override 
    public String process(JsonElement element) { 
     JsonObject obj = element.getAsJsonObject(); 
     int frameType = obj.get("frameType").getAsInt(); 

     switch(frameType) { 
      case 4: return "Gem"; 
      case 5: return "Currency"; 
     } 
     if (obj.get("typeLine").getAsString().contains("Map") 
       && obj.get("descrText").getAsString() != null 
       && obj.get("descrText").getAsString().contains("Travel to this Map")) { 
      return "Map"; 
     } 

     return "Equipment"; 
    } 
} 

Cách sử dụng:

RuntimeTypeAdapterFactory<Item> itemAdapter = RuntimeTypeAdapterFactory.of(Item.class, new ItemTypePredicate()) 
     .registerSubtype(Currency.class) 
     .registerSubtype(Equipment.class) 
     .registerSubtype(Gem.class) 
     .registerSubtype(Map.class); 

Gson gson = new GsonBuilder() 
     .enableComplexMapKeySerialization() 
     .registerTypeAdapterFactory(itemAdapter).create(); 

Lớp cơ sở hierachy là Mục. Tiền tệ, thiết bị, đá quý và bản đồ tất cả mở rộng này.

+0

Đây gần như những gì tôi muốn, nhưng yêu cầu cơ bản của tôi là xác định các lớp học không liên quan, mà tôi nghĩ là không thể. – Abe

Các vấn đề liên quan