如何将任何对象序列化为URI? [英] How to serialize ANY Object into a URI?

查看:128
本文介绍了如何将任何对象序列化为URI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基本问题:是否有任何自动构建的内容(不必是流行的库/包的一部分)?我正在使用的主要内容是Spring(MVC)和Jackson2。

My basic question: is there anything built that already does this automatically (doesn't have to be part of a popular library/package)? The main things I'm working with are Spring (MVC) and Jackson2.

我知道有一些手动方法可以做到这一点:

I understand there are a few manual ways to do this:


  1. 在每个类中创建一个方法,将其特定属性序列化为 property = value& 表单(因为很臭)它是一堆逻辑重复,我觉得)。

  2. 创建一个接受一个对象的函数,并使用反射动态读取所有属性(我想是getters),并构建字符串通过获得每个。我假设这是杰克逊一般用于序列化/反序列化的方式,但我真的不知道。

  3. 使用Jackson的某些功能来自定义序列化对象。我已经研究过自定义序列化程序,但它似乎是特定于一个类(所以我必须为每个我正在尝试序列化的类创建一个),而我希望有一个通用的方法。我只是在理解如何将一个普遍应用于对象时遇到困难。一些链接:

  1. Create a method in each class that serializes its specific properties into property=value& form (kind of stinks because it's a bunch of logic duplication, I feel).
  2. Create a function that accepts an object, and uses reflection to dynamically read all the properties (I guess the getters), and build the string by getting each. I'm assuming this is how Jackson works for serialization/deserialization in general, but I really don't know.
  3. Use some feature of Jackson to customly serialize the object. I've researched custom serializers, but it seems they are specific to a class (so I'd have to create one for each Class I'm trying to serialize), while I was hoping for a generic way. I'm just having trouble understanding how to apply one universally to objects. A few of the links:
    • http://techtraits.com/Programming/2011/11/20/using-custom-serializers-with-jackson/
    • http://wiki.fasterxml.com/JacksonHowToCustomSerializers

我的主要帖子调查是 Java:获取属性一个班级的合作nstruct一个字符串表示

我的观点是我有几个我希望能够序列化的类,而不必为每个类指定特定的东西。这就是为什么我认为使用反射的函数(上面的#2)是解决这个问题的唯一方法(如果我必须手动完成)。

My point is that I have several classes that I want to be able to serialize without having to specify something specific for each. That's why I'm thinking a function using reflection (#2 above) is the only way to handle this (if I have to do it manually).

如果它有帮助,我的意思的一个例子就是说,这两个类:

If it helps, an example of what I mean is with, say, these two classes:

public class C1 {
    private String C1prop1;
    private String C1prop2;
    private String C1prop3;

    // Getters and setters for the 3 properties
}

public class C2 {
    private String C2prop1;
    private String C2prop2;
    private String C2prop3;

    // Getters and setters for the 3 properties
}

(不,属性名称和约定不是我的实际应用程序使用的,它只是一个示例)

(no, the properties names and conventions are not what my actual app is using, it's just an example)

序列化的结果将是 C1prop1 =值& C1prop2 =值& C1prop3 =值 C2prop1 =值& C2prop2 =值& C2prop3 =值,但只有一个地方定义了序列化的发生方式(已在某处定义,或由我手动创建)。

The results of serializing would be C1prop1=value&C1prop2=value&C1prop3=value and C2prop1=value&C2prop2=value&C2prop3=value, but there's only one place that defines how the serialization happens (already defined somewhere, or created manually by me).

所以我的想法是我必须最终使用以下形式(取自我上面链接的帖子):

So my idea is that I will have to end up using a form of the following (taken from the post I linked above):

public String toString() {
    StringBuilder sb = new StringBuilder();
    try {
        Class c = Class.forName(this.getClass().getName());
        Method m[] = c.getDeclaredMethods();
        Object oo;
        for (int i = 0; i < m.length; i++)
        if (m[i].getName().startsWith("get")) {
            oo = m[i].invoke(this, null);
            sb.append(m[i].getName().substring(3) + ":"
                      + String.valueOf(oo) + "\n");
        }
    } catch (Throwable e) {
        System.err.println(e);
    }
    return sb.toString();
}

并修改它以接受一个对象,并更改所附项目的格式到 StringBuilder 。这对我有用,我现在不需要帮助修改它。

And modify it to accept an object, and change the format of the items appended to the StringBuilder. That works for me, I don't need help modifying this now.

所以再次,我的主要问题是,是否有一些东西已经处理了这个(可能是简单的)序列化我必须(快速)修改上面的功能,即使我必须指定如何处理每个属性和值以及如何组合每个?

So again, my main question is if there's something that already handles this (potentially simple) serialization instead of me having to (quickly) modify the function above, even if I have to specify how to deal with each property and value and how to combine each?

如果它有帮助,这个背景是我使用 RestTemplate (Spring)向不同的服务器发出GET请求,我想传递一个特定对象的属性/值在URL中。我知道我可以使用类似的东西:

If it helps, the background of this is that I'm using a RestTemplate (Spring) to make a GET request to a different server, and I want to pass a specific object's properties/values in the URL. I understand I can use something like:

restTemplate.getForObject("URL?C1prop1={C1Prop1}&...", String.class, C1Object);

我相信这些属性会自动映射。但就像我说的那样,我不想为每种对象类型创建不同的URL模板和方法。我希望有以下内容:

I believe the properties will be automatically mapped. But like I said, I don't want to have to make a different URL template and method for each object type. I'm hoping to have something like the following:

public String getRequest(String url, Object obj) {
    String serializedUri = SERIALIZE_URI(obj);
    String response = restTemplate.getForObject("URL?" + serializedUri, String.class);
    return response;
}

其中 SERIALIZE_URI 是在哪里处理它。我可以称之为 getRequest(whatever,C1Object); getRequest(whateverElse,C2Object);

where SERIALIZE_URI is where I'd handle it. And I could call it like getRequest("whatever", C1Object); and getRequest("whateverElse", C2Object);.

推荐答案

我认为,解决方案编号4是可以的。它很容易理解和清楚。

I think, solution number 4 is OK. It is simple to understand and clear.

我提出了类似的解决方案,我们可以使用 @JsonAnySetter 注释。请看下面的例子:

I propose similar solution in which we can use @JsonAnySetter annotation. Please, see below example:

import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonProgram {

    public static void main(String[] args) throws Exception {
        C1 c1 = new C1();
        c1.setProp1("a");
        c1.setProp3("c");

        User user = new User();
        user.setName("Tom");
        user.setSurname("Irg");

        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.convertValue(c1, UriFormat.class));
        System.out.println(mapper.convertValue(user, UriFormat.class));
    }
}

class UriFormat {

    private StringBuilder builder = new StringBuilder();

    @JsonAnySetter
    public void addToUri(String name, Object property) {
        if (builder.length() > 0) {
            builder.append("&");
        }
        builder.append(name).append("=").append(property);
    }

    @Override
    public String toString() {
        return builder.toString();
    }
}

以上程序打印:

prop1=a&prop2=null&prop3=c
name=Tom&surname=Irg

您的getRequest方法可能如下所示:

And your getRequest method could look like this:

public String getRequest(String url, Object obj) {
    String serializedUri = mapper.convertValue(obj, UriFormat.class).toString();
    String response = restTemplate.getForObject(url + "?" + serializedUri, String.class);
    return response;
}

这篇关于如何将任何对象序列化为URI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆