2016-11-11 208 views
1

说我有一个对象,我将它的所有属性都存储为纯JSON。有没有一种方法来存储.getClass()值,以便能够检索它并获取原始对象?将字符串值转换为类型

例:

class foo 
{ 
int test; 
String classType; 
} 


//other class 
foo demo = new foo(); 
demo.classType = demo.getClass().toString(); 


//I'm not entirely sure how to convert classType into a type I can use to parse back the data, like so: 
foo demo2 = (demo.classType)jsonData; 

由于这可能是一个有点宽泛的问题,我会接受的答案,只是告诉我上面有哪些是所谓的(如果你将一个搜索词)。

+1

你只是试图在进程之间/网络之间传递一个对象?你有没有考虑过使一个对象可序列化? – dahui

+0

它作为响应对象的一部分(作为有效载荷)传递,所以我不认为我可以使用可序列化。 – Gabrielus

+0

使用'Serializable'作为有效载荷并没有什么本质的错误(尽管它有很多痛苦点使它不受欢迎)。 [协议缓冲区](https://developers.google.com/protocol-buffers/)是Google解决此问题的解决方案,如果您有[Gson](https://github.com/google/gson)是另一个有用的工具需要坚持使用JSON。 – dimo414

回答

1

转换Java对象到JSON

ObjectMapper mapper = new ObjectMapper(); 
Staff obj = new Staff(); 

//Object to JSON in file 
mapper.writeValue(new File("c:\\file.json"), obj); 

//Object to JSON in String 
String jsonInString = mapper.writeValueAsString(obj); 

转换JSON到Java对象

ObjectMapper mapper = new ObjectMapper(); 
String jsonInString = "{'name' : 'mkyong'}"; 

//JSON from file to Object 
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class); 

//JSON from URL to Object 
Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class); 

//JSON from String to Object 
Staff obj = mapper.readValue(jsonInString, Staff.class); 
2

您可以使用instanceof操作员创建并投射新创建的对象至foo

foo demo = new foo(); 
    demo.classType = demo.getClass().toString(); 

    foo demo2 = null; 
    OtherClass demo3 = null; 

     Class<?> clas=Class.forName(demo.getClass().getName()); 
     Object obj= clas.newInstance(); 
     if (obj instanceof foo) { 
      demo2=(foo)obj; 
     }else if (obj instanceof OtherClass) { 
      demo3=(OtherClass)obj; 
     }   

注:确保如果您使用多个else,如果再分等级后在上面,超类添加子类状态,是的,你需要添加try-catch块太

+0

有很多类,我会有许多if子句全部做类似的事情 - 这意味着demo3 =(OtherClass)obj;有没有办法进一步简化?例如:clas demo2 =(clas)obj; – Gabrielus

+0

要使用某些类的特定功能,您必须使用向下转换。你可以直接使用外壳,但是'if'条件可以覆盖不确定性,因为我们只是说'clas.newInstance()'返回一个'bar'并且'foo demo2 =(foo)obj'是一个错误,而另一个方法将会使用越来越多的反射来查找和调用'foo'类的所有方法 –

相关问题