Home > OS >  Gson Parse Json with List<String>
Gson Parse Json with List<String>

Time:01-11

I have a class with some fields:

public class GsonRepro {
    class A {
        private List<String> field1 = new ArrayList<>();
        private String name;
        private Integer status;

        public A(){
        }

        public List<String> getfield1() { return field1; }
        public void setField1(List<String> field1) { this.field1 = field1; }

        public String getName() { return name; }
        public void setName() { this.name = name; }

        public Integer getStatus() { return status; }
        public void setStatus(int status) { this.status = status; }
    }

    public static void main(String[] args) {
        String str = "{\"name\":\"my-name-1\",\"status\":0,\"field1\":[\"0eac6b1d3d494c2d8568cd82d9d13d5f\"]}";
        A a = new Gson().fromJson(str, A.class);
    }
}

All fields are parsed but the List<String> field1, how can I get this to work?

Solution:

The code above works just fine. Initially, I just had a typo in the List field.

CodePudding user response:

I tried with the code as above that you shared and is working fine without any issues. Please check following code and verify,

public static void main(String[] args) {
    String str = "{\"name\":\"my-name-1\",\"status\":0,\"field1\":[\"0eac6b1d3d494c2d8568cd82d9d13d5f\"]}";
    A a = new Gson().fromJson(str, A.class);
    System.out.println(a.getName());
    System.out.println(a.getStatus());
    System.out.println(a.getfield1());
}

Following is the output which is being printed on console as,

my-name-1
0
[0eac6b1d3d494c2d8568cd82d9d13d5f]

CodePudding user response:

you can try to use TypeToken like in this answer to another question.

For you it would look like this:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

...

Type type = new TypeToken<A>(){}.getType();
A a = new Gson().fromJson(str, type);

Greetings

CodePudding user response:

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

class A {
    private List<String> field1 = new ArrayList<>();
    private String name;
    private Integer status;

    public A() {
    }

    public List<String> getfield1() {
        return field1;
    }

    public void setField1(List<String> field1) {
        this.field1 = field1;
    }

    public String getName() {
        return name;
    }

    public void setName() {
        this.name = name;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }
}

public class GsonParseList {
    public static void main(String[] args) {
        String str = "{'name':'my-name-1','status':0,'field1':['0eac6b1d3d494c2','d8568cd82d9d13d5f']}";
        A a = new Gson().fromJson(str, A.class);
        System.out.println(a.getfield1());
    }
}

CodePudding user response:

Idk is that helps you but I have a request like this in the below

public void getCheckPointLocationViaQRCode(String QRResource) {


    RequestModel<String> req = new RequestModel<String>();

    req.data = QRResource;


    AppRepository.get_instance().apiHandler.post(AppRepository.get_instance().BASE_URL   "workorder/validateQR", req, new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            // Something went wrong
        }

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

            if (response.isSuccessful()) {

                try {
                    requireActivity().runOnUiThread(() -> {


                        //MODEL OLUŞTUR SONRA BAŞLA
                        String result = null;
                        try {
                            result = Objects.requireNonNull(response.body()).string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        Gson gson = new Gson();
                        Type collectionType = new TypeToken<ResponseModel<WorkOrderLocation>>() {
                        }.getType();
                        ResponseModel<WorkOrderLocation> resultResponseModel = gson.fromJson(result, collectionType);

                        System.out.println("DÖNEN SONUCUM"   resultResponseModel.data.title);

                        ImageView success = new ImageView(requireActivity());

                        AlertDialog.Builder builder =
                                new AlertDialog.Builder(requireActivity()).
                                        setMessage("QR KOD OKUMA BAŞARILI")
                                        .setPositiveButton("DEVAM ET", (dialogInterface, i) -> {
                                            dialogInterface.dismiss();

                                            Bundle arguments = new Bundle();
                                            arguments.putString("QRResult", resultResponseModel.data.latitude   " "   resultResponseModel.data.longitude);
                                            MyPatrolFragment myPatrolFragment = new MyPatrolFragment();

                                            myPatrolFragment.setArguments(arguments);

                                            FragmentTransaction fragmentTransaction = getParentFragmentManager().beginTransaction();

                                            fragmentTransaction.replace(R.id.fragmentContainerView, myPatrolFragment).addToBackStack("tag").commit();
                                        }).
                                        setView(success);
                        builder.show();
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(e);
                }
            } else {
                Toast.makeText(requireActivity(), "İşlem Başarısız Lütfen Tekrar Deneyin", Toast.LENGTH_SHORT).show();
            }
        }
    });


}

I use like this Hope it helps you

  •  Tags:  
  • Related