我有一个返回的json字符串:
[{"TRAIN_JOURNEY_STAFF[],"ID":15,"EMAIL_ADDRESS":"jk@connectedrail.com","PASSWORD":"test","FIRST_NAME":"Joe","LAST_NAME":"Kevin","DATE_OF_BIRTH":"1996-04-20T00:00:00","GENDER":"Male","STAFF_ROLE":"Conductor","PHOTO":null},{new record..}]
这里有几条记录,我找不到将这种json字符串转换为单个对象的方法。我正在使用以下内容读取数据:
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
}
我尝试了简单的json库,但是解析器将字符串混合了,这并不理想,因为我需要将数据逐行输出到jtables。
任何帮助将不胜感激。
使用GSON在下面解决了该问题。非常感谢大家!
JsonElement jelement = new JsonParser().parse(response.toString());
JsonArray jarray = jelement.getAsJsonArray();
JsonObject jobject = jarray.get(0).getAsJsonObject();
System.out.println(jobject.get("FIRST_NAME"));
答案 0 :(得分:1)
您可以使用以下内容:
public class ObjectSerializer {
private static ObjectMapper objectMapper;
@Autowired
public ObjectSerializer(ObjectMapper objectMapper) {
ObjectSerializer.objectMapper = objectMapper;
}
public static <T> T getObject(Object obj, Class<T> class1) {
String jsonObj = "";
T userDto = null;
try {
jsonObj = objectMapper.writeValueAsString(obj);
userDto = (T) objectMapper.readValue(jsonObj, class1);
System.out.println(jsonObj);
} catch (JsonProcessingException jpe) {
} catch (IOException e) {
e.printStackTrace();
}
return userDto;
}
将您的JSON对象传递给带有类名的此方法alogn,它将把JSON数据设置为该相应的类。
注意: 类必须具有与要映射的JSON中相同的变量。
答案 1 :(得分:0)
基本上你是这样的:
[
{
"TRAIN_JOURNEY_STAFF":[
],
"ID":15,
"EMAIL_ADDRESS":"jk@connectedrail.com",
"PASSWORD":"test",
"FIRST_NAME":"Joe",
"LAST_NAME":"Kevin",
"DATE_OF_BIRTH":"1996-04-20T00:00:00",
"GENDER":"Male",
"STAFF_ROLE":"Conductor",
"PHOTO":null
},
{
}
]
您可以使用JSON构造函数将此数组序列化为JSONObjects
的数组。
尝试在Java中寻找JSONObject
和JSONArray
类。
构造函数基本上采用字符串化的JSON(您已经拥有)。
答案 2 :(得分:0)
答案 3 :(得分:0)
您可以使用 Jackson 将JSON转换为对象。包括依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
然后创建一个POJO类以存储JSON.pojo类应反映json字符串结构并应具有适当的字段以映射值(此处示例代码Staff.class是pojo类)。然后使用ObjectMapper您可以将JSON字符串转换为java对象的类,如下所示:
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(response.toString(), Staff.class);
读取JSON字符串并将其转换为对象的另一种简单的方法是:
JSON字符串:
{
"lastName":"Smith",
"address":{
"streetAddress":"21 2nd Street",
"city":"New York",
"state":"NY",
"postalCode":10021
},
"age":25,
"phoneNumbers":[
{
"type":"home", "number":"212 555-1234"
},
{
"type":"fax", "number":"212 555-1234"
}
],
"firstName":"John"
}
public class JSONReadExample
{
public static void main(String[] args) throws Exception
{
// parsing file "JSONExample.json"
Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));
// typecasting obj to JSONObject
JSONObject jo = (JSONObject) obj;
// getting firstName and lastName
String firstName = (String) jo.get("firstName");
String lastName = (String) jo.get("lastName");
System.out.println(firstName);
System.out.println(lastName);
// getting age
long age = (long) jo.get("age");
System.out.println(age);
// getting address
Map address = ((Map)jo.get("address"));
// iterating address Map
Iterator<Map.Entry> itr1 = address.entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
// getting phoneNumbers
JSONArray ja = (JSONArray) jo.get("phoneNumbers");
// iterating phoneNumbers
Iterator itr2 = ja.iterator();
while (itr2.hasNext())
{
itr1 = ((Map) itr2.next()).entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
}
}
供参考:
https://www.geeksforgeeks.org/parse-json-java/
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/