简体   繁体   English

将RestTemplate与Spring for Android结合使用时如何在Abstract类中设置属性

[英]How to set a property in Abstract class when using RestTemplate with Spring for Android

I am using Spring for Android to request data from my restful server and gson to Converter json to Java objetct without accessing any function in the object. 我正在使用Spring for Android来从我的静态服务器和gson请求数据,将Converter json转换为Java objetct,而无需访问对象中的任何函数。
As there is a json property "user_id", what I want to save this as the primary key of the sqlite data after convertion. 由于有一个json属性“ user_id”,我想在转换后将其保存为sqlite数据的主键。
The problem is my sqlite library defined a "mId" property as the primary key in abstract class.And gson convert is not using a "set function" to set the property. 问题是我的sqlite库在抽象类中定义了一个“ mId”属性作为主键。而gson convert不使用“设置函数”来设置该属性。 The only thing I want is turn user_id to mId properly. 我唯一想要的就是将user_id正确地设置为mId。

Here is the code: 这是代码:
1. the abstract class to access sqlite: 1.访问sqlite的抽象类:

public abstract class Model {
    protected Long mId = null;
    public final Long getId() {
        return mId;
    }

    public void setId(Long id){
        mId = id;
    }

    public void saveToSqlite(){
        //using mId;
    }
}

2.An class for restful user data: 2.一个用于释放用户数据的类:

public class User extends Model implements Serializable{
    private static final long serialVersionUID = 1L;
    @SerializedName("user_id")
    private Long userId;

    public Long getUserId() {
        return userId;
    }

    //this function is not accessed when user object generated
    public void setUserId(Long userId) {
        this.userId = userId;
        this.setId(userId);
    }
}

3.request and convert code: 3.请求并转换代码:

RestTemplate restTemplate = new RestTemplate();
GsonHttpMessageConverter jsonConverter = new GsonHttpMessageConverter();
restTemplate.getMessageConverters().add(jsonConverter);
final String url = "http://restful.test.com/users";
User[] users = restTemplate.getForObject(url, User[].class);

Declare a custom deserializer for your class. 为您的类声明一个自定义解串器。 Something like the one below. 类似于下面的那个。

Quote - The model 报价-模型

class Quote
{
    private String symbol;
    private String test; // the empty field we want to populate

    // getters() setters()
}

QuoteCreator deserializer - Populate test from symbol QuoteCreator反序列化器-从符号填充测试

class QuoteCreator implements JsonDeserializer<Quote>
{

    public Quote deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException
    {
        Gson g = new Gson();
        Quote a = g.fromJson(json, Quote.class);
        a.setTest(a.getSymbol());
        return a;
    }
}

Run

GsonBuilder b = new GsonBuilder();
b.registerTypeAdapter(Quote.class,new QuoteCreator());
Gson create = b.create();
Quote fromJson = (Quote) create.fromJson(file, Quote.class);

It works. 有用。 You can use a more generic reflective solution to catch hold of a variety of classes, but its easier if the JSON is just corrected instead of resorting to a work around like this. 您可以使用更通用的反射解决方案来捕获各种类,但是如果仅更正JSON而不是像这样变通,则更容易。

Generic deserializer 通用解串器

class MyCreator<T> implements JsonDeserializer<T>
{

    public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException
    {
        try
        {
            Gson g = new Gson();
            T a = g.fromJson(json, typeOfT);
            Class<? extends Object> class1 = a.getClass();
            Method getter = class1.getMethod("getSymbol", null);
            Method setter = class1.getMethod("setTest", String.class);
            String symbol = (String) getter.invoke(a, null);
            setter.invoke(a, symbol);
            return a;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
}

Usage 用法

b.registerTypeAdapter(Quote.class,new MyCreator<Quote>());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring RestTemplate:在配置类中设置时覆盖ResponseErrorHandler不起作用 - Spring RestTemplate : Overridding ResponseErrorHandler not working when set in Configuration class 使用 Spring RestTemplate 时如何避免 [] 的双重编码? - How to avoid double-encoding of [] when using Spring RestTemplate? 使用Spring Oauth2RestTemplate时如何切换到服务用户 - How to switch to a service user when using Spring Oauth2RestTemplate 使用 SimpleClientHttpRequestFactory 时,如何使自定义 RestTemplate 使用标准 Spring Boots 的 Prometheus RestTemplate 指标进行检测? - How to make custom RestTemplate to instrument with standard Spring Boots' Prometheus RestTemplate metrics when using SimpleClientHttpRequestFactory? Spring设置了抽象bean属性值 - Spring set abstract bean property value 使用Spring时获取HttpMessageNotReadableException异常-RestTemplate - Get HttpMessageNotReadableException Exception when using Spring - RestTemplate 在Java中使用Spring RestTemplate时发生NullPointedException - NullPointedException when using Spring RestTemplate in Java 如何将Class值设置为spring bean属性? - How to set Class value to spring bean property? 如何使用 Spring 集成处理 resttemplate 中的 ResourceAccessException - How to handle ResourceAccessException in resttemplate using Spring integration 如何在 Spring Boot 中使用 RestTemplate 发送表情符号? - How to Send Emojis using RestTemplate in Spring Boot?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM