我遇到下面显示的代码问题。下面的代码如下生成json:
[{“ id”:123,“ subjects”:“ English”},{“ id”:456,“ subjects”:“ Maths”}]
我们可以看到在生成的JSON中缺少名称标签。我不明白何时返回学生列表,由于在“名称”类型的学生类中有一个属性,因此,所得的json应该包含名称标签。请帮忙!
PS:我已经在debug中获取了代码,我看到“ students arraylist” 0索引和索引确实包含名称prpoperty以及id和subject。但是JSON不包含此属性。
Restcontroller:
<android.support.design.widget.FloatingActionButton
android:id="@+id/Main_FAB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
学生Bean类:
package com.example.demo;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@SpringBootApplication
@RestController
public class Demo1Application {
@Autowired
Student student;
List<Student> students = new ArrayList<>();
@RequestMapping(value="/getStudents", method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
public List<Student> getstudent () {
students = student.setStudent();
return students;
}
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
System.out.println("Hello");
}
}
名称Bean类:
package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class Student {
int id;
String Subject;
@Autowired
@Qualifier("name")
Name name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSubjects() {
return Subject;
}
public void setSubject(String subject) {
Subject = subject;
}
public void setName(String Fname, String Mname, String Lname) {
Name nm = new Name();
name = nm.setfullname(Fname,Mname,Lname) ;
}
public Student(int id, String Subject) {
this.id = id;
this.Subject = Subject;
}
public Student() {
System.out.println("Student Object created");
}
public List<Student> setStudent() {
List<Student> Students = new ArrayList<>();
Student s = new Student ();
Student s1 = new Student ();
s.setId(123);
s.setSubject("English");
s.setName("Hemant", "123", "Mamod");
s1.setId(456);
s1.setSubject("Maths");
s1.setName("Akshay", "123", "pandey");
Students.add(s);
Students.add(s1);
return Students;
}
}
答案 0 :(得分:2)
问题在于您没有在Name
类中获得Student
的知识。
请按照以下步骤添加吸气剂:
@Component
public class Student {
int id;
String Subject;
Name name;
/******/
public Name getName() {
return name;
}
}
谈到带有NullPinterException
属性的name
-这意味着它由于某些原因尚未自动接线,因此在您的情况下,您可以删除@Autowired
和@Qualifier
注释或找出自动装配有什么问题