Android 원생 json 과 fastjson 의 간단 한 사용

7057 단어 Androidjsonfastjson
안 드 로 이 드 네 이 티 브 조작 제 이 슨 데이터
주로 두 가지 JSONobject 작업 대상 입 니 다.     JONSArray 조작 json 배열
대상

//          
    Student student=new Student();
    student.setAge(23);
    student.setClazz("   ");
    student.setName("    ");
    //  JSONObject 
    JSONObject jsonObject=new JSONObject();
    //         
    jsonObject.put("age",student.getAge());
    jsonObject.put("name",student.getName());
    jsonObject.put("clazz",student.getClazz());
    //   json   
    String json=jsonObject.toString();
     //    
    Log.e("ObjectToJson",json);
로그 로그 표시

json 대상
JSONobject 를 새로 만 들 고 json 문자열 을 구조 적 으로 할당 합 니 다.   이 JSONobject 대상 은 json 값 을 가지 고 있 습 니 다.     그리고 대상 의 할당 을 만 듭 니 다.  JSONobject 는 유형 별 값 에 대해 get 방법 이 다 릅 니 다.

 JSONObject jsonObject=new JSONObject(json);
 Student student=new Student();
 student.setName(jsonObject.getString("name"));
 student.setClazz(jsonObject.getString("clazz"));
 student.setAge(jsonObject.getInt("age"));
 Log.e("JsonToObject",student.getName()+"======"+student.getClazz()+"===="+student.getAge());

리스트 
JONSArray 사용 하기

//      
List<Student> students=new ArrayList<Student>();
students.add(student);
students.add(student);
//    JSONArray 
JSONArray jsonArray=newJSONArray();
//      
for(inti=0;i<students.size();i++){
  //      
  Studentstu=students.get(i);
  //  JSONObject 
  JSONObject jo=newJSONObject();
  //  
  jo.put("age",stu.getAge());
  jo.put("name",stu.getName());
  jo.put("clazz",stu.getClazz());
  // JSONObject    JSONArray 
  jsonArray.put(jo);
}
//toString  json
String json=jsonArray.toString();
Log.e("ListToJson",json);

json 등급 리스트

//  JSONArray json  
JSONArray jsonArray=new JSONArray(json);
//      
Student students=new ArrayList<Student>();
Log.e("BeforeJsonToList","    "+students.size());
//  jsonArray
for(inti=0;i<jsonArray.length();i++){
  //  JSONObject  
  JSONObject jsonObject=jsonArray.getJSONObject(i);
  //      
  Student stu=new Student();
  //  
  jsonObject.put("age",stu.getAge());
  jsonObject.put("name",stu.getName());
  jsonObject.put("clazz",stu.getClazz());
  //           
  students.add(stu);
}
Log.e("AfterJsonToList","    "+students.size());

메모:JSONobject 와 JSONarray 를 사용 하 는 과정 에서 이상 을 포착 해 야 합 니 다.
귀 찮 지 않 습 니까?데이터 가 많 으 면 정말 피곤 합 니 다.
간단 해 지 는 방법 은 역사상 가장 빠 른 json 조작 이 라 고 불 리 는 fastjson.jar 를 다운로드 하 는 것 이다.  아 리 제품  그리고 사용 하면 간단 해 요
FastJSon 조작 데이터
대상

//      
Student student=new Student();
student.setClazz("  ");
student.setAge(23);
student.setName("  ");
//     json 
String json=JSON.toJSONString(student);
Log.e("ObjectToJson",json);
한 마디 로 끝 났 습 니 다.있 을 정도 로 간단 합 니 다.   마 운 똥 고마워!!!

json 대상

 // json       1json   2    
 Student student=JSON.parseObject(json,Student.class);
 Log.e("JsonToObject","=========="+student.getName());
한 마디  안 드 로 이 드 원생 에 비해 정말 감동 적 입 니 다.

list

List<Student>stuList=new ArrayList<Student>();
stuList.add(student);
stuList.add(student);
stuList.add(student);
//List   json
json=JSON.toJSONString(stuList);
Log.e("ListToJson","=========="+json);
집합 에 세 개의 같은 대상 을 추가 하 였 다.   json 문자열 의 출력 은 ref,{0}이 됩 니 다.  첫 번 째 대상 을 인용 한 것 이 분명 하 다.     같은 상 대 를 추 가 했 으 니까.   fastjson 은 만 들 지 않 습 니 다.  직접 참조  이것 도 그 가 가장 빠르다 고 불 리 는 원인 이다.
근 데 그 에 따 른 문제 가 있어 요.     fastjson 식별 참조 다른 jar 인식 하지 않 음        하면,만약,만약...  클 라 이언 트 사용 gson  어쩌면 좋아
1.모두 fastjson 사용
2.제 이 슨 을 돌 릴 때 속성 설정    반복 참조 대상 을 사용 하지 않 으 면 okjson=JSON.toJSONString(stuList,SerializerFeature.DisableCircularReferenceDetect);
json 회전 목록

 stuList=JSON.parseArray(json,Student.class);
 Student student1=stuList.get(0);
 Log.e("JsonToList","====================="+student1.getName());

가끔  대상 의 모든 필드 가 필요 하지 않 습 니 다.    이때 속성 필 터 를 설정 할 수 있 습 니 다.  필요 하지 않 은 필드 를 걸 러 내 라.

//          PropertyFilter
    json=JSON.toJSONString(stuList, new PropertyFilter() {
      @Override//  1              2          3    
      public boolean apply(Object o, String s, Object o1) {
        Log.e("PropertyFilter",o+"======"+s+"==============="+o1);
        if (s.equals("name")){
          return false;
        }else{
          return true;
        }
      }
    });
    Log.e("PropertyFilter",json);
name 필터 설정   로그 로그

한 가지 상황 을 소개 하고 있 습 니 다.
일반적인 클래스 를 정의 하 였 습 니 다.
학생 대상 과 문자열 이 들 어 있 습 니 다.

대상 을 제 이 슨 으로 바꾸다

우리 가 이 제 이 슨 을 대상 으로 바 꾸 려 고 할 때 문제 가 생 겼 어 요.

이때 TypeReference 류 를 실현 하여 대상 을 밀봉 해 야 합 니 다.

완벽 하 게 해결 하 다  범 형 이 있 는 모든 것 은 TypeReference 를 사용 할 수 있다.

마지막 으로 사이트 하나 소개 해 드릴 게 요http://json.cn/   아주 강력 합 니 다.제 이 슨 을 자동 으로 포맷 합 니 다.   문법 오류 가 있 으 면 잘못 보고 할 수도 있 습 니 다.
이상 은 본 고의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.또한 저 희 를 많이 지지 해 주시 기 바 랍 니 다!

좋은 웹페이지 즐겨찾기