转换LinkedHashMap< String,String>到Java中的对象 [英] Convert LinkedHashMap<String,String> to an object in Java

查看:233
本文介绍了转换LinkedHashMap< String,String>到Java中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将直接从我的问题开始,稍后我会提供更多背景信息。

I'll start directly with my question and later on I give more background information.

简单:我有一个 LinkedHashMap< String,String> ,它代表一个具体对象。
将它转换为该对象的最佳方法是什么?

Simple: I hava a LinkedHashMap<String, String> and it represents a specific object. What is the best way to convert it to that object?

我知道您可以使用泛型来遍历所有元素并设置字段,但什么是嵌套对象?

I know that you can use generics to get through all elements and set the fields, but what is whit nested objects?

背景:我有一个消耗JSON对象的JAX-RS服务。我的服务处理不同类型的对象,只代表一个接口。所以我不知道哪些对象来自外部以及哪个程序正在使用我的服务。

Background: I have a JAX-RS service that consumes JSON objects. My service handles different kind of objects and just represents an interface. So I don't know which objects are coming from outside and which program is using my service.

在运行时,我通过界面上的 @Inject 获取信息。 JAX-RS服务将来自客户端的数据存储在无类型的Object中,并自动完成(即 LinkedHashMap< String,String> )。

At runtime I get the information via @Inject on my interface. The JAX-RS service stores the data from the client in an untyped Object and its done automatically (thats the LinkedHashMap<String, String>).

使用我的界面,我想提供类似 setObject 的方法,参数应该是该类型的对象。我可以处理所有这些,但不是我将Object LinkedHashMap< String,String> 转换为该特定对象的部分。

With my interface I want to provide a method like setObject and parameter should be a object of that type. I can handle all of this, but not the part where I convert the Object LinkedHashMap<String, String> to that specific object.

示例结构
目标对象可能喜欢

Example Structure: Target Objects could like that

public class Document {
    private String title;
    private String id;
    private int version;
}

LinkedHashMap 看起来喜欢那样

{title=some title, id=1, version=1}


推荐答案

您可以创建两个类

@XmlAccessorType(XmlAccessType.FIELD) 
public class Document {
    @XmlElement
    private String title;
    @XmlElement
    private String id;
    @XmlElement
    private int version;
}  


@XmlAccessorType(XmlAccessType.FIELD)
public class MapJson {
    @XmlElement
    private LinkedHashMap<String, String> documents; 
}  

和cobvert对象到JSON使用

杰克逊

and cobvert Object to JSON usingg
Jackson

new org.codehaus.jackson.map.ObjectMapper().writeValueAsString(instanceofMapJson);  

Google JSON

Google JSON

new com.google.gson.Gson().toJson(instanceofMapJson);  

PS。使用google json,您可以从类中删除xml注释

PS. Using google json, you can remove xml annotations from your classes

这篇关于转换LinkedHashMap&lt; String,String&gt;到Java中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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