>  기사  >  웹 프론트엔드  >  JSON의 문자열 문자열과 Java의 List 객체 간 변환

JSON의 문자열 문자열과 Java의 List 객체 간 변환

高洛峰
高洛峰원래의
2017-01-18 10:01:271522검색

프런트 엔드:
1. List 객체에서 json을 변환하면 json을 직접 탐색하여 데이터를 읽을 수 있습니다.
2. 프런트엔드 List 객체를 json으로 변환하여 백엔드로 보내야 하는 경우 param은 ajax 매개변수이며 변환은 다음과 같습니다.

var jsonStr = JSON.stringify(list);
var param= {};
param.jsonStr=jsonStr;

백엔드:
1. 문자열을 목록으로 변환(str은 목록으로 변환)

List<T> list = new ArrayList<T>();
JSONArray jsonArray = JSONArray.fromObject(str);//把String转换为json
list = JSONArray.toList(jsonArray,t);//这里的t是Class<T>

2. 목록을 json으로 변환

JSONArray json = JSONArray.fromObject(object);
String str = json.toString();//把json转换为String

예:
1. 페이지 사용자가 입력한 정보를 기반으로 Answer 개체 목록을 구성합니다.

/**
  * @param answers
  * @param question_ids
  * @param types
  * @return
  */
 private List<Answer> toAnswerList(String[] studenAnswers, int[] question_ids,
   int[] types,int[] scores) {
  List<Answer> answerList = new ArrayList<Answer>();
    
  if(studenAnswers!=null && question_ids!= null && types!= null&& scores!= null){
   for (int i = 0; i < studenAnswers.length; i++) {
      
    Answer answer = new Answer();
    String studenAnswer = studenAnswers[i];
    int type = types[i];
    int question_id = question_ids[i];
    int score = scores[i];
    
      
    answer.setQuestion_id(question_id);
    answer.setScore(score);
    answer.setStudenAnswer(studenAnswer);
    answer.setType(type);
      
    answerList.add(answer);
   }
  }
  return answerList;
 }
  
 /**
  * 将一个json字串转为list
  * @param props
  * @return
  */
 public static List<Answer> converAnswerFormString(String answer){
  if (answer == null || answer.equals(""))
   return new ArrayList();
  
  JSONArray jsonArray = JSONArray.fromObject(answer);
  List<Answer> list = (List) JSONArray.toCollection(jsonArray,
    Answer.class);
    
  return list;
 }

2. 고객 기반 Answer 객체 목록에서 사용자가 최종 페이지에 입력한 정보에서 생성

public String getAnswerString(String[] studenAnswers, int[] question_ids,
  int[] types,int[] scores) {
 List list = toAnswerList(studenAnswers, question_ids,
    types, scores);
 JSONArray jsonarray = JSONArray.fromObject(list);
 
 return jsonarray.toString();
}

JSON 문자열 문자열 및 Java List 객체 변환과 관련된 더 많은 기사를 보려면 다음을 참고하세요. PHP 중국어 웹사이트!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.