Type of objects inside non-parameterized arrays in JSON

青春壹個敷衍的年華 提交于 2019-12-25 17:42:33

问题


I am trying to write simple function that converts Json strings into Objects.

The language I am using is objective-c however this question discusses issues doesn't relate to this lang.

My question is, How to know the Type of Objects that laid inside a json array that is to be mapped into non-parameterized (a.k.a non-generic) lists??

I found two Json Java libraries unable to solve this issue, Jakson and Gson and here's the example:

import java.io.Serializable;
import java.util.List;

import com.google.gson.Gson;


public class Main
{
    public static void main(String[] args) throws Exception
    {
        Gson g = new Gson();
        Office o =  g.fromJson(
                "{\"empx\":\"1\",\"emps\":[{\"firstName\":\"Muhammad\",\"lastName\":\"Abdullah\"},{\"firstName\":\"XX\",\"lastName\":null}]}"
                , Office.class);
        System.out.println(((Employee)o.getEmps().get(0)).getFirstName());
    }
}

class Office
{
    private List emps;
    private String empx;

    public String getEmpx()
    {
        return empx;
    }
    public void setEmpx(String empx)
    {
        this.empx = empx;
    }

    public List getEmps()
    {
        return emps;
    }

    public void setEmps(List emps)
    {
        this.emps = emps;
    }
}


class Employee implements Serializable
{
    private static final long serialVersionUID = 1L;
    String firstName;
    String lastName;

    public String getFirstName()
    {
        return firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }

    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }
}

In Google Gson they considered this array's objects as objects of type java.lang.Object:

Exception in thread "main" java.lang.ClassCastException: java.lang.Object

But Jaskon was much smarter, it considered this unknown object to be a Map:

Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap

However, Both have been failed to detect the Object (which I think is impossible!)

So, In a language that doesn't support Parameterized types (Generics), Is n't any way to accomplish this?


回答1:


I would suggest using dictionaries. The key keys could infer the types or there could be a type key.



来源:https://stackoverflow.com/questions/7560989/type-of-objects-inside-non-parameterized-arrays-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!