简体   繁体   English

将json对象转换为java对象

[英]convert json object into java object

class A{}

class B{}

class C{ 
       private Map<A,B> myMap;
   }

class Test{

public static void main(String [] args)
{ 
      Map classMap=new HashMap();
       classMap.put("myMap","?");
       C c = (C) JSONObject.toBean(jsonObject, C.class,classMap);
}

}

I am using "net.sf.json" library for converting json object into java object.Here in class C there is a map, so how to convert it into Java Object. 我使用“net.sf.json”库将json对象转换为java对象。在C类中有一个映射,所以如何将它转换为Java Object。 Here jsonObject is a json representation of class C. My question is how to convert a json object into Java Object if java Object containing Map 这里jsonObject是类C的json表示形式。我的问题是,如果java对象包含Map,如何将json对象转换为Java Object?

I am a beginner, any help will be very thankful. 我是初学者,任何帮助都会非常感激。

I have used jackson library and in that when a json is passed to the java code and if you want to parse that json into a java object you need to have a class which contains all the property which are present in the json string. 我使用过杰克逊库,并且当将json传递给java代码时,如果您要将json解析为java对象,则需要具有一个包含json字符串中存在的所有属性的类。

for example: 例如:

jsonString=
{
 'firstname':'json',
 'lastname':'jack'
}

will be equivalent to a java class which contains both the property as 将等同于包含属性as的java类

class A {
 String firstname;
 String lastname;
}

so if you accept the string from frontend as the object of class A it works 因此,如果您接受来自前端的字符串作为A类的对象,它就可以工作

like 喜欢

public void (A objectofA){

}

and you call this method from front end and pass a json string using json library it will work and have faith in your work. 然后从前端调用此方法,并使用json库传递json字符串,它将起作用并且对您的工作充满信心。

I don't know how to do it in "net.sf.json" Try to see how serialization works in "net.sf.json". 我不知道如何在“net.sf.json”中执行此操作尝试查看序列化在“net.sf.json”中的工作原理。 Probably, you can go from there. 可能您可以从那里去。

This is how it is done using jackson, (one of the commenters has tried to explain you an approach using this) 这是使用杰克逊的方式,(其中一位评论者试图向您解释使用此方法的方法)

//you need to import:
//import org.codehaus.jackson.map.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(c) //--> This gives Json String

I don't think this can work, as JSON cannot represent arbitrary objects as keys in maps. 我认为这行不通,因为JSON无法将任意对象表示为地图中的键。 In JSON keys have to be strings. 在JSON中,键必须是字符串。 So in your example Map would only work if A was String. 因此,在您的示例中,Map仅在A为字符串的情况下才有效。

Then you could say: 然后你可以说:

classMap.put("myMap",B.class);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM