【问题标题】:How to send a JSON object with an array of objects in it to the spring controller?如何将包含对象数组的 JSON 对象发送到 spring 控制器?
【发布时间】:2015-12-01 10:46:34
【问题描述】:

我有两个使用 Hibernate @OneToMany 映射的域模型。我正在尝试在前端创建一个 JSON 对象并将其发送到 spring mvc 控制器以自行设置模型数据。

以下是我的模型类: ConceptModelDetails.java

@Entity
@Table(name="conceptModelDetails")
@SequenceGenerator(name="CONCEPT_SEQ",sequenceName="concept_sequence", initialValue=1, allocationSize=1)
public class ConceptModelDetails implements java.io.Serializable{
    private static final long serialVersionUID = 1L;
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="CONCEPT_SEQ")
    private int instructionsId;
    private String operationType;
    private String conceptModelID;
    private String requestor;
    private String status;
    private Timestamp requestDateTime;
    private Timestamp lastExecutedDateTime;
    private Timestamp completedDateTime;
    @OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="conceptModelDetails")
    @JsonManagedReference   // nested exception is org.springframework.http.converter.HttpMessageNotWritableException: 
    //Could not write JSON: Infinite recursion
//The fix is to get Jackson to be able to handle bi-directional references
    private List<Instructions> instructions = new ArrayList<Instructions>(); 




    public ConceptModelDetails() {
        // TODO Auto-generated constructor stub
    }


//setter & getter methods        
}

和 Instructions.java:

@Entity
@Table(name="instructions")
@SequenceGenerator(name="INSTRUCTIONS_SEQ", sequenceName="instructions_sequence",initialValue=1, allocationSize=1)
public class Instructions implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="INSTRUCTIONS_SEQ")
    private int Sno;
    private String instruction;
    @ManyToOne
    @JoinColumn(name="instructionsId")
    @JsonBackReference
    private ConceptModelDetails conceptModelDetails;


    //setter & getter methods
}

这是我在前端创建和发送 JSON 对象的 send 方法:

$scope.send = function() {
    console.log("test");
    var dataObj = {
        "operationType" : $scope.operationType,
        "conceptModelID" : $scope.conceptID,
        "requestor" : $scope.requestor,
        "status" : "new",
        "requestDateTime" : null,
        "lastExecutedDateTime" : null,
        "completedDateTime" : null,
        "instructions" : null

    };
    console.log(dataObj);
    dataObj.instructions = [];    
    console.log($scope.operations_publish);
    var ins = getSelected();
    for ( var i in ins) {
        var temp = {

            instruction : null,
            conceptModelDetails : null

        }
        temp.instruction = ins[i];
        dataObj.instructions.push(temp);
    }
    var response = $http.post(
            'PostService', dataObj);
    response.success(function(data, status, headers, config) {
        $scope.responseData = data;
    });
    response.error(function(data, status, headers, config) {
        alert("Exception details: " + JSON.stringify({
            data : data
        }));
    });
}

以下是我的控制器:

@RequestMapping(value = "/PostService", method = RequestMethod.POST)
public @ResponseBody String Test(@RequestBody ConceptModelDetails conceptModelDetails){
    ApplicationContext context = new ClassPathXmlApplicationContext(
            "applicationContext.xml");
    ConceptModelDAO obj = (ConceptModelDAO) context.getBean("objDAO");
    System.out.println("concept id: "+conceptModelDetails.getConceptModelID()+" "+ conceptModelDetails.getInstructionsId());
    System.out.println("instructions id: "+conceptModelDetails.getInstructions());
    // ConceptModelDAOImpl objDAO = new ConceptModelDAOImpl();
    obj.add(conceptModelDetails);
    Instructions instructions = new Instructions();
    System.out.println("dimba: " + instructions.getInstruction());
    ArrayList<Instructions> operations = (ArrayList<Instructions>) conceptModelDetails.getInstructions();
    for (int i = 0; i< operations.size(); i++ ) {
        instructions.setInstruction(operations.get(i).getInstruction());
        instructions.setConceptModelDetails(conceptModelDetails);
        obj.addInstructions(instructions);
    }
    return null;
}

由于List&lt;Instructions&gt; instructions,我收到错误:400(错误请求)。请建议我如何处理。

【问题讨论】:

  • 能否请您发布堆栈跟踪以了解您将在日志中遇到的异常?
  • 向我们展示从 UI 发布的 JSON。
  • @DeepakKumar:这是错误:org.hibernate.collection.internal.PersistentBag 无法转换为 java.util.ArrayList。已解决。谢谢。

标签: java angularjs json hibernate spring-mvc


【解决方案1】:

我在这段代码中发现了问题。正如博卓所解释的here,
ArrayList&lt;Instructions&gt; operations = (ArrayList&lt;Instructions&gt;) conceptModelDetails.getInstructions();

应该是

List&lt;Instructions&gt; operations = conceptModelDetails.getInstructions(); 在弹簧控制器中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2014-10-20
    • 2014-10-31
    • 2013-09-26
    • 2016-09-09
    相关资源
    最近更新 更多