简体   繁体   English

如何将json字符串转换为bean列表?

[英]How can I convert a json string to a bean list?

I get a JsonString: 我得到一个JsonString:

{
   "student[0].firstName":"asdf",
   "student[0].lastName":"sfd",
   "student[0].gender":"1",
   "student[0].foods":[
      "Steak",
      "Pizza"
   ],
   "student[0].quote":"Enter your favorite quote!",
   "student[0].education":"Jr.High",
   "student[0].tOfD":"Day",
   "student[1].firstName":"sf",
   "student[1].lastName":"sdf",
   "student[1].gender":"1",
   "student[1].foods":[
      "Pizza",
      "Chicken"
   ],
   "student[1].quote":"Enter your favorite quote!",
   "student[1].education":"Jr.High",
   "student[1].tOfD":"Night"
}

the Student bean: 学生豆:

public class Student {
    private String firstName;
    private String lastName;
    private Integer gender;
    private List<String> foods;
    private String quote;
    private String education;
    private String tOfD;
    getXxx()...;
    setXxx()...;
}

I want to use jackson to convert the JsonString to List。 我想用jackson将JsonString转换为List。

In fact, I want to post two form content in one form,use ajax. 实际上,我想在一个表单中发布两个表单内容,使用ajax。 And in the SpringMVC handler method, i want get like List or Student[] type paramter,then use directly. 在SpringMVC处理程序方法中,我希望得到List或Student []类型参数,然后直接使用。 I hope spring can resolver it , or use other util jar do this. 我希望春天可以解决它,或使用其他工具罐做到这一点。

<form action="" method="post">
First Name:<input type="text" name="student[0].firstName" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="student[0].lastName" maxlength="36" size="12"/> <br/>
Gender:<br/>
Male:<input type="radio" name="student[0].gender" value="1"/><br/>
Female:<input type="radio" name="student[0].gender" value="0"/><br/>
Favorite Food:<br/>
Steak:<input type="checkbox" name="student[0].foods" value="Steak"/><br/>
Pizza:<input type="checkbox" name="student[0].foods" value="Pizza"/><br/>
Chicken:<input type="checkbox" name="student[0].foods" value="Chicken"/><br/>
<textarea wrap="physical" cols="20" name="student[0].quote" rows="5">Enter your favorite quote!</textarea><br/>
Select a Level of Education:<br/>
<select name="student[0].education">
    <option value="Jr.High">Jr.High</option>
    <option value="HighSchool">HighSchool</option>
    <option value="College">College</option>
</select><br/>
Select your favorite time of day:<br/>
<select size="3" name="student[0].tOfD">
    <option value="Morning">Morning</option>
    <option value="Day">Day</option>
    <option value="Night">Night</option>
</select>

First Name:<input type="text" name="student[1].firstName" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="student[1].lastName" maxlength="36" size="12"/> <br/>
Gender:<br/>
Male:<input type="radio" name="student[1].gender" value="1"/><br/>
Female:<input type="radio" name="student[1].gender" value="0"/><br/>
Favorite Food:<br/>
Steak:<input type="checkbox" name="student[1].foods" value="Steak"/><br/>
Pizza:<input type="checkbox" name="student[1].foods" value="Pizza"/><br/>
Chicken:<input type="checkbox" name="student[1].foods" value="Chicken"/><br/>
<textarea wrap="physical" cols="20" name="student[1].quote" rows="5">Enter your favorite quote!</textarea><br/>
Select a Level of Education:<br/>
<select name="student[1].education">
    <option value="Jr.High">Jr.High</option>
    <option value="HighSchool">HighSchool</option>
    <option value="College">College</option>
</select><br/>
Select your favorite time of day:<br/>
<select size="3" name="student[1].tOfD">
    <option value="Morning">Morning</option>
    <option value="Day">Day</option>
    <option value="Night">Night</option>
</select>

<p><input type="submit"/></p>

Your JSON , if it is representing a collection of students should resemble the following. 您的JSON,如果它代表学生集合,应该类似于以下内容。 The difference is this is a collection of student represented as a JSON Array (as opposed to a monolithic student1,student2 object etc.) 区别在于这是一个表示为JSON数组的学生集合(而不是单一的student1,student2对象等)

[
    {
        "firstName": "asdf",
        "lastName": "sfd",
        "gender": "1",
        "foods": [
            "Steak",
            "Pizza"
        ],
        "quote": "Enter your favorite quote!",
        "education": "Jr.High",
        "tOfD": "Day"
    },
    {
        "firstName": "sf",
        "lastName": "sdf",
        "gender": "1",
        "foods": [
            "Pizza",
            "Chicken"
        ],
        "quote": "Enter your favorite quote!",
        "education": "Jr.High",
        "tOfD": "Night"
    }
]

If this is the structure , conversion to the bean is a one liner using Google's GSON library 如果这是结构,转换到bean是使用谷歌的GSON库的单线程

Gson gson = new Gson();
Student[] student = gson.fromJson(<your string here>, Student[].class);

Now is the tricky part , i have an upstream system which uses some kind of string functions than using JSON libraries and can shell out JSON as you provided. 现在是棘手的部分,我有一个上游系统使用某种字符串函数而不是使用JSON库,并且可以像你提供的那样发出JSON。 You will have to use a lot of string manipulation and also wish that the format above does not change in the toString() representation of whoever gives you the data from the source (There is an excellent best practice by Joshua Bloch in Effective Java about this one). 您将不得不使用大量的字符串操作,并且还希望上面的格式不会在任何从源代码中提供数据的toString()表示中更改(Joshua Bloch在Effective Java中有一个关于此的优秀最佳实践一)。

None the less, i am posting a piece of code that works (but should never be used in any form of production quality code). 尽管如此,我发布了一段有效的代码(但绝不应该用于任何形式的生产质量代码)。 This can be rolled up may be as a single regex , in the interest of readability it is not done. 这可以卷起来作为单个正则表达式,为了便于阅读,它没有完成。 Use this for understanding only , because a larger collection can quickly choke things up. 使用它只是为了理解,因为更大的集合可以迅速扼杀。 You can also explore a Streaming JSON parser like JACKSON may be and take it one element at a time , i have left that out in purpose as an exercise. 你也可以像JACKSON一样探索一个流式JSON解析器,并一次把它作为一个元素,我把它留作目的作为练习。 Hope this helps 希望这可以帮助

Gson gson = new Gson();
String jsonInString = "{\"student[0].firstName\": \"asdf\",\"student[0].lastName\": \"sfd\",\"student[0].gender\": \"1\",\"student[0].foods\":[\"Steak\",\"Pizza\"],\"student[0].quote\": \"Enter your favorite quote!\",\"student[0].education\": \"Jr.High\",\"student[0].tOfD\": \"Day\",\"student[1].firstName\": \"sf\",\"student[1].lastName\": \"sdf\",\"student[1].gender\": \"1\",\"student[1].foods\": [\"Pizza\",\"Chicken\"],\"student[1].quote\": \"Enter your favorite quote!\",\"student[1].education\": \"Jr.High\",\"student[1].tOfD\": \"Night\"}";
String jsonWithoutArrayIndices = jsonInString.replaceAll("\\[\\d\\]", "").replaceAll("student.","");
String jsonAsCollection = "[" + jsonWithoutArrayIndices + "]";
String jsonAsValidCollection = jsonAsCollection.replaceAll(",\"student.firstName\"","},{\"student.firstName\"");
System.out.println(jsonAsValidCollection);
Student[] students = gson.fromJson(jsonAsValidCollection, Student[].class);
System.out.println("-----------------------------------------------");
System.out.println(students[0]);
System.out.println("-----------------------------------------------");

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

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