source

Android에서 개체를 JSON으로 변환

factcode 2022. 8. 21. 14:06
반응형

Android에서 개체를 JSON으로 변환

Android에서 객체를 JSON으로 간단하게 변환할 수 있는 방법이 있습니까?

대부분의 사용자가 gson을 사용하고 있습니다.이것을 체크해 주세요.

Gson gson = new Gson();
String json = gson.toJson(myObj);
public class Producto {

int idProducto;
String nombre;
Double precio;



public Producto(int idProducto, String nombre, Double precio) {

    this.idProducto = idProducto;
    this.nombre = nombre;
    this.precio = precio;

}
public int getIdProducto() {
    return idProducto;
}
public void setIdProducto(int idProducto) {
    this.idProducto = idProducto;
}
public String getNombre() {
    return nombre;
}
public void setNombre(String nombre) {
    this.nombre = nombre;
}
public Double getPrecio() {
    return precio;
}
public void setPrecio(Double precio) {
    this.precio = precio;
}

public String toJSON(){

    JSONObject jsonObject= new JSONObject();
    try {
        jsonObject.put("id", getIdProducto());
        jsonObject.put("nombre", getNombre());
        jsonObject.put("precio", getPrecio());

        return jsonObject.toString();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    }

}

더 나은 선택:

@Override
public String toString() {
    return new GsonBuilder().create().toJson(this, Producto.class);
}

라이브러리 Gradle 다운로드:

implementation 'com.google.code.gson:gson:2.8.2'

라이브러리를 메서드로 사용합니다.

Gson gson = new Gson();

//transform a java object to json
System.out.println("json =" + gson.toJson(Object.class).toString());

//Transform a json to java object
String json = string_json;
List<Object> lstObject = gson.fromJson(json_ string, Object.class);

Android용 Spring은 RestTemplate를 사용하여 이를 쉽게 수행할 수 있습니다.

final String url = "http://192.168.1.50:9000/greeting";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Greeting greeting = restTemplate.getForObject(url, Greeting.class);

Android 3.0(API 레벨 11)에서는 Android의 JSON 파서가 보다 최신으로 향상되었습니다.

http://developer.android.com/reference/android/util/JsonReader.html

토큰 스트림으로서 JSON(RFC 4627) 부호화된 값을 읽습니다.이 스트림에는 리터럴 값(스트링, 숫자, 부울 및 늘)과 개체 및 배열의 시작 및 끝 구분 기호가 모두 포함됩니다.토큰은 JSON 문서에 나타나는 순서와 같은 깊이 우선 순서로 통과됩니다.JSON 개체 내에서 이름과 값의 쌍은 단일 토큰으로 표시됩니다.

잭슨 라이브러리를 사용하여(프로젝트로 가져오기) 현재 객체 클래스를 사용하여 직렬화 또는 직렬화를 취소하는 변환 메서드를 만들 수도 있습니다.

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

private String convertObjectToJson(ObjectClass object) {
        ObjectMapper mapper = new ObjectMapper();
        //By default all fields without explicit view definition are included, disable this
        mapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, false);

        String jsonString = "";

        try {
            jsonString = mapper.writerWithView(ObjectClass.class).writeValueAsString(object);
            System.out.println(jsonString);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return jsonString;
    }

이렇게 하면 여러 뷰를 사용하여 POST/PUT/PATCH 작업에서 서로 다른 JSON 개체 문자열을 전송할 수 있습니다.

언급URL : https://stackoverflow.com/questions/5571092/convert-object-to-json-in-android

반응형