programing

데이터 객체 배열을 json으로 변환 - Android

minecode 2023. 3. 26. 13:04
반응형

데이터 객체 배열을 json으로 변환 - Android

현재 webView 프런트 엔드를 탑재한 네이티브 안드로이드 앱 작업을 하고 있습니다.

다음과 같은 것이 있습니다.

public class dataObject
{
  int a;
  String b;
}

그리고 활동 중에,

dataObject 배열을 만들었습니다(예: dataObject x[5];

이 5개의 dataObject를 javascript webView인터페이스에 콜백 함수로 JSON으로 전달합니다.

인터넷을 검색해보니 대부분의 튜토리얼에서는 변환 방법에 대해 언급하고 있는 것 같습니다.fromJson()...에 관한 것은 많지 않다.toJson()그런 걸 알게 된 게 있어요dataObject.toJson(), 가 동작합니다.

5개의 dataObjects를 모두 통과하려면 어떻게 해야 합니까?

다음은 Gson을 개체 목록과 함께 사용하는 방법에 대한 포괄적인 예입니다.이 예에서는 Json으로 변환하는 방법, 목록 참조 방법 등을 정확하게 보여 줍니다.

Test.java:

import com.google.gson.Gson;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;


public class Test {

  public static void main (String[] args) {

    // Initialize a list of type DataObject
    List<DataObject> objList = new ArrayList<DataObject>();
    objList.add(new DataObject(0, "zero"));
    objList.add(new DataObject(1, "one"));
    objList.add(new DataObject(2, "two"));

    // Convert the object to a JSON string
    String json = new Gson().toJson(objList);
    System.out.println(json);

    // Now convert the JSON string back to your java object
    Type type = new TypeToken<List<DataObject>>(){}.getType();
    List<DataObject> inpList = new Gson().fromJson(json, type);
    for (int i=0;i<inpList.size();i++) {
      DataObject x = inpList.get(i);
      System.out.println(x);
    }

  }


  private static class DataObject {
    private int a;
    private String b;

    public DataObject(int a, String b) {
      this.a = a;
      this.b = b;
    }

    public String toString() {
      return "a = " +a+ ", b = " +b;
    }
  }

}

컴파일 방법:

javac -cp "gson-2.1.jar:." Test.java

마지막으로 실행:

java -cp "gson-2.1.jar:." Test

Windows 를 사용하고 있는 경우는, 다음의 순서로 전환할 필요가 있습니다.:와 함께;를 참조해 주세요.

실행 후 다음 출력이 표시됩니다.

[{"a":0,"b":"zero"},{"a":1,"b":"one"},{"a":2,"b":"two"}]
a = 0, b = zero
a = 1, b = one
a = 2, b = two

이는 명령행 프로그램일 뿐이지만 Android 환경(참조 jarlibs 등)에서도 동일한 원칙이 적용됩니다.

도우미 클래스를 사용한 내 버전의 gson 목록 역직렬화:

public List<E> getList(Class<E> type, JSONArray json) throws Exception {
    Gson gsonB = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    return gsonB.fromJson(json.toString(), new JsonListHelper<E>(type));
}



public class JsonListHelper<T> implements ParameterizedType {

  private Class<?> wrapped;

  public JsonListHelper(Class<T> wrapped) {
    this.wrapped = wrapped;
  }

  public Type[] getActualTypeArguments() {
    return new Type[] {wrapped};
  }

  public Type getRawType() {
    return List.class;
  }

  public Type getOwnerType() {
    return null;
  }

}

사용.

List<Object> objects = getList(Object.class, myJsonArray);

언급URL : https://stackoverflow.com/questions/9186806/gson-turn-an-array-of-data-objects-into-json-android

반응형