programing

Gson 라이브러리를 사용하여 JSON 문자열을 어떻게 변환합니까?

copysource 2022. 8. 27. 23:31
반응형

Gson 라이브러리를 사용하여 JSON 문자열을 어떻게 변환합니까?

Gson 라이브러리를 사용하여 JSON 문자열을 어떻게 변환합니까?

ArrayList

커스텀 클래스의

JsonLog

기본적으로는

JsonLog

SMS 로그, 통화 로그, 데이터 로그 등 Android 앱에 의해 작성된 다양한 종류의 로그에 의해 구현되는 인터페이스입니다.

ArrayList

모든 것을 모은 것입니다.6번째 줄에 오류가 계속 나요.

public static void log(File destination, JsonLog log) {
    Collection<JsonLog> logs = null;
    if (destination.exists()) {
        Gson gson = new Gson();
        BufferedReader br = new BufferedReader(new FileReader(destination));
        logs = gson.fromJson(br, ArrayList<JsonLog>.class); // line 6
        // logs.add(log);
        // serialize "logs" again
    }
}

컴파일러는 제가 타입을 참조하고 있다는 것을 이해하지 못하는 것 같습니다.

ArrayList

.내가 어떻게 해야 하나요?

You may use TypeToken to load the json string into a custom object.

logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());

Documentation:

Represents a generic type T.

Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

예를 들어 다음과 같은 유형의 리터럴을 작성하려면

List<String>

빈 어나니머스 내부 클래스를 만들 수 있습니다.

TypeToken<List<String>> list = new TypeToken<List<String>>() {};

이 구문을 사용하여 다음과 같은 와일드카드 매개 변수가 있는 유형 리터럴을 만들 수 없습니다.

Class<?>

또는

List<? extends CharSequence>

.

Kotlin:

If you need to do it in Kotlin you can do it like this:

val myType = object : TypeToken<List<JsonLong>>() {}.type
val logs = gson.fromJson<List<JsonLong>>(br, myType)

Or you can see this answer for various alternatives.

Your JSON sample is:

{
    "status": "ok",
    "comment": "",
    "result": {
    "id": 276,
    "firstName": "mohamed",
    "lastName": "hussien",
    "players": [
            "player 1",
            "player 2",
            "player 3",
            "player 4",
            "player 5"
    ]
}

so if you want to save arraylist of modules in your SharedPrefrences so :

1- will convert your returned arraylist for json format using this method

public static String toJson(Object jsonObject) {
    return new Gson().toJson(jsonObject);
}

2- Save it in shared prefreneces

PreferencesUtils.getInstance(context).setString("players", toJson((.....ArrayList you want to convert.....)));

3- to retrieve it at any time get JsonString from Shared preferences like that

String playersString= PreferencesUtils.getInstance(this).getString("players");

4- convert it again to array list

public static Object fromJson(String jsonString, Type type) {
    return new Gson().fromJson(jsonString, type);
}

ArrayList<String> playersList= (ArrayList<String>) fromJson(playersString,
                    new TypeToken<ArrayList<String>>() {
                    }.getType());

this solution also doable if you want to parse ArrayList of Objects Hope it's help you by using Gson Library .

Kotlin

data class Player(val name : String, val surname: String)

val json = [
  {
    "name": "name 1",
    "surname": "surname 1"
  },
  {
    "name": "name 2",
    "surname": "surname 2"
  },
  {
    "name": "name 3",
    "surname": "surname 3"
  }
]

val typeToken = object : TypeToken<List<Player>>() {}.type
val playerArray = Gson().fromJson<List<Player>>(json, typeToken)

OR

val playerArray = Gson().fromJson(json, Array<Player>::class.java)

Why nobody wrote this simple way of converting JSON string in List ?

List<Object> list = Arrays.asList(new GsonBuilder().create().fromJson(jsonString, Object[].class));

If you want to use Arrays, it's pretty simple.

logs = gson.fromJson(br, JsonLog[].class); // line 6

를 제공하다

JsonLog

배열로서

JsonLog[].class

If you want convert from Json to a typed ArrayList , it's wrong to specify the type of the object contained in the list. The correct syntax is as follows:

 Gson gson = new Gson(); 
 List<MyClass> myList = gson.fromJson(inputString, ArrayList.class);

I am not sure about gson but this is how you do it with Jon.sample hope there must be similar way using gson

{ "Players": [ "player 1", "player 2", "player 3", "player 4", "player 5" ] }

===============================================

import java.io.FileReader;
import java.util.List;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JosnFileDemo {

    public static void main(String[] args) throws Exception
    {
        String jsonfile ="fileloaction/fileName.json";


                FileReader reader = null;
                JSONObject jsb = null;
                try {
                    reader = new FileReader(jsonfile);
                    JSONParser jsonParser = new JSONParser();
                     jsb = (JSONObject) jsonParser.parse(reader);
                } catch (Exception e) {
                    throw new Exception(e);
                } finally {
                    if (reader != null)
                        reader.close();
                }
                List<String> Players=(List<String>) jsb.get("Players");
                for (String player : Players) {
                    System.out.println(player);
                }           
    }
}

You have a string like this.

"[{"id":2550,"cityName":"Langkawi","hotelName":"favehotel Cenang Beach - Langkawi","hotelId":"H1266070"},
{"id":2551,"cityName":"Kuala Lumpur","hotelName":"Metro Hotel Bukit Bintang","hotelId":"H835758"}]"

Then you can covert it to ArrayList via Gson like

var hotels = Gson().fromJson(historyItem.hotels, Array<HotelInfo>::class.java).toList()

HotelInfo 클래스는 다음과 같습니다.

import com.squareup.moshi.Json

data class HotelInfo(

    @Json(name="cityName")
    val cityName: String? = null,

    @Json(name="id")
    val id: Int? = null,

    @Json(name="hotelId")
    val hotelId: String? = null,

    @Json(name="hotelName")
    val hotelName: String? = null
)

인코틀린 송신용 : Arraylist를 송신하는 경우

Gson().toJson(arraylist)

수신용:Array List를 수신한 경우

var arraylist = Gson().fromJson(argument, object : TypeToken<ArrayList<LatLng>>() {}.type)  

송신용 : ModelClass (예: LatLgModel.class)를 송신하는 경우

var latlngmodel = LatlngModel()
latlngmodel.lat = 32.0154
latlngmodel.lng = 70.1254

Gson().toJson(latlngModel)

수신용:Model Class를 받는 경우

var arraylist = Gson().fromJson(argument,LatLngModel::class.java )  

언급URL : https://stackoverflow.com/questions/12384064/gson-convert-from-json-to-a-typed-arraylistt

반응형