反序列化json错误:LinkedTreeMap

时间:2018-04-17 12:18:54

标签: android

我在这里搜索了stackoverflow,但我仍然找不到解决方案,所以我的问题。

我创建了这个方法来反序列化即将发布的json(必须是通用的,因为所有调用都在这里传递):

public class GsonUtil {

    public static Gson createGsonObject() {

        // Formado de data alterado, outro formato não estava convertendo
        // Alterado para setar // na saída devido problema com WebService
        GsonBuilder builder = new GsonBuilder();

        builder.setDateFormat(GsonUtil.FORMAT_DATE).create();

       ..............

        //ARRAY
        builder.registerTypeAdapter(List.class, new JsonArrayListDeserializer());

        //HOW TO DO
        //builder.registerTypeAdapter(List.class, new JsonArrayListSerializer());

        Gson gson = builder.create();

        return gson;
    }
        private static class JsonArrayListDeserializer<T> implements JsonDeserializer<ArrayList<T>>{

        @Override
        public ArrayList<T> deserialize(JsonElement jsonElement, java.lang.reflect.Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            try {

                Gson gson = new Gson();
                TypeToken<ArrayList<T>> token = new TypeToken<ArrayList<T>>() {};
                ArrayList<T> value = gson.fromJson(jsonElement, token.getType());

                return value;
            } catch (ClassCastException e) {
                throw new JsonParseException("Cannot parse json Boolean '"
                        + jsonElement.toString() + "'", e);
            }
        }
    }
}

创建此方法后,数据开始到达适配器,但尝试在视图中插入时会出现错误。

这是错误:

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to br.com.sisteplan.evida.atendimento.service_atendimento.vo.AgendamentoVo
                                                                                        at br.com.sisteplan.evida.atendimento.adapters.CustomRecyclerViewAdapterAt.getUsuarioVo(CustomRecyclerViewAdapterAt.java:90)

片段:

  public class FragmentAtendidos extends Fragment implements CustomRecyclerViewAdapterAt.onViewHolderClicksMedicamentosAdapter {

    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private CustomRecyclerViewAdapterAt mAdapter;
    private View view;
    private Spinner spinner;
    private ArrayList<AgendamentoVo> atendidosVos;
    private RetornoAtendidosVo retornoAtendidosVo;

    .....

        @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.fragment_recycler_view_at);
        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);
        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);

        // specify an adapter (see also next example)
        mAdapter = new CustomRecyclerViewAdapterAt(atendidosVos,
                (AppCompatActivity) getActivity(), this);

        mRecyclerView.setAdapter(mAdapter);
    }

    .....

        @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ..
        new AsyncTaskListarAtendidos(FragmentAtendidos.this.getFragmentManager(), false).execute(profissionalVo);
    }

    ...

     private class AsyncTaskListarAtendidos extends BaseAsyncTask<ProfissionalVo,Void,AsyncTaskResult<RetornoAtendidosVo>> {

        private FragmentManager mFragmentManager;
        private ProfissionalVo profissionalVo;

        public AsyncTaskListarAtendidos(FragmentManager fragmentManager, boolean isDialogShow) {
            super(fragmentManager, isDialogShow);
            this.mFragmentManager = fragmentManager;
        }

        @Override
        protected AsyncTaskResult doInBackground(ProfissionalVo... profissionalVos) {

            try {
                profissionalVo = profissionalVos[0];

                RetornoAtendidosVo retorno = ServiceAgendamentosAtendidos.getInstance(MyApplicationInstance.getInstanceApplicationSingleton().getDsChaveAcessoWbs())
                        .consultaAtendidos(profissionalVo);

                return new AsyncTaskResult<RetornoAtendidosVo>(retorno);
            }catch (Exception e){
                return new AsyncTaskResult<Retorno>(e);
            }
        }

        @Override
        protected void onPostExecute(AsyncTaskResult<Retorno> respProfissionalVO) {
            super.onPostExecute(respProfissionalVO);

            if (respProfissionalVO.getExceptionResult() == null && getActivity() != null){
                retornoAtendidosVo = (RetornoAtendidosVo) respProfissionalVO.getResult();
                retornoAtendidosVo.getRetorno();
                atendidosVos = (ArrayList<AgendamentoVo>)retornoAtendidosVo.getRetorno();

                mAdapter = new CustomRecyclerViewAdapterAt(atendidosVos,(AppCompatActivity)getActivity(),this);

                mRecyclerView.setAdapter(mAdapter);
            }
        }
    }

}

我的适配器:

public class CustomRecyclerViewAdapterAt extends
        RecyclerView.Adapter<CustomRecyclerViewAdapterAt.ViewHolder>
        implements OnClickListener {

    private AppCompatActivity appCompatActivity;
    private Object mClassListner;
    private ArrayList<AgendamentoVo> mDataset;
    // Animation
    private int lastPosition = -1;

    // Provide a suitable constructor (depends on the kind of dataset)
    public CustomRecyclerViewAdapterAt(ArrayList<AgendamentoVo> myDataset, AppCompatActivity appCompatActivity, Object classListner) {

        this.appCompatActivity = appCompatActivity;
        mDataset = myDataset;
        this.mClassListner = classListner;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(
            ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.cell_item_atendidos, parent, false);
        // set the view's size, margins, paddings and layout parameters

        ViewHolder vh = new ViewHolder(v);

        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        AgendamentoVo pacienteVo = getUsuarioVo(position);

        // Configura a view com o Id do Agendamento
        holder.mLinearLayout.setTag(position);
        holder.mTextViewNome.setText(pacienteVo.getPaciente().getNmUsuario() != null ? pacienteVo.getPaciente().getNmUsuario() : "Branco");
        /*holder.mTextViewIdade.setText(mDataset.get(position).getPaciente().getIdade() != null ? mDataset.get(position).getPaciente().getIdade() : "Branco2");*/
//        holder.mTextViewIdadeDescricao.setText(pacienteVo.getIdade() != null ? pacienteVo.getIdade() : "");

        /**
         *Configuração de ouvintes de click *
         */
        holder.mLinearLayout.setOnClickListener(this);

        // Here you apply the animation when the view is bound
        setAnimation(holder.mCardView, position);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {

        if (mDataset != null) {
            SavedPreferences.setQtdHistorico(appCompatActivity, mDataset.size());
            return mDataset.size();
        }
        return 0;
    }

    public AgendamentoVo getUsuarioVo(int position) {

        return mDataset.get(position);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.cell_item_at_linearlayout_content:

                ((onViewHolderClicksMedicamentosAdapter) mClassListner)
                        .onCellClickContent(v);
                break;
            default:
                break;
        }

    }

    /**
     * Here is the key method to apply the animation
     */
    private void setAnimation(View viewToAnimate, int position) {
        // If the bound view wasn't previously displayed on screen, it's
        // animated
        if (position > lastPosition) {

            Animation animation = AnimationUtils.loadAnimation(
                    appCompatActivity, android.R.anim.slide_in_left);
            // Animation animation = AnimationUtils.loadAnimation(
            // appCompatActivity, R.anim.slide_top_to_bottom);
            // Animation animation =
            // AnimationUtils.loadAnimation(appCompatActivity,
            // R.anim.clockwise_rotation);
            // animation.setRepeatCount(Animation.START_ON_FIRST_FRAME);
            viewToAnimate.startAnimation(animation);

            lastPosition = position;
        }
    }

    /**
     * Interface para notificação do click nos layouts
     *
     * @author Erick Brittes
     */
    public static interface onViewHolderClicksMedicamentosAdapter {

        /**
         * @param caller
         */
        public void onCellClickContent(View caller);
    }

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class ViewHolder extends RecyclerView.ViewHolder {

        public CardView mCardView;

        public LinearLayout mLinearLayout;
        public AppCompatTextView mTextViewNome;
        public AppCompatTextView mTextViewIdade;
        public AppCompatTextView mTextViewIdadeDescricao;

        public ViewHolder(View v) {
            super(v);

            mCardView = (CardView) v
                    .findViewById(R.id.cell_item_at_cardview);

            mLinearLayout = (LinearLayout) v
                    .findViewById(R.id.cell_item_at_linearlayout_content);

            mTextViewNome = (AppCompatTextView) v
                    .findViewById(R.id.cell_item_at_textview_nome_paciente);

            mTextViewIdade = (AppCompatTextView) v
                    .findViewById(R.id.cell_item_at_textview_idade);

            mTextViewIdadeDescricao = (AppCompatTextView) v
                    .findViewById(R.id.cell_item_at_textview_content_idade_descricao);

        }
    }
}

LogCat带我到这个错误行:

holder.mTextViewNome.setText(pacienteVo.getPaciente().getNmUsuario() != null ? pacienteVo.getPaciente().getNmUsuario() : "Branco");

我该怎么做才能解决此错误? 谢谢!

编辑:

我的适配器中的结果:

enter image description here

1 个答案:

答案 0 :(得分:0)

序列化和反序列化通用类型的情况。这可能对您有所帮助MSDN