lundi 13 avril 2020

Problem about using Filed.set() to inject an array of Java Beans

  • Description

    When I was trying to make a JSON-Parser (convert json string into Java bean), I met a little problem.
    As you can see, here're two regular beans - Student & Address:
public class Student {
    private byte age;
    private Address[] addresses;
    // etc.
}
public class Address {
    private String country;
    private String province;
    private String city;
    // etc.
}

And I got a json like this:

{age:32,
 addresses:[
    {country:"USA",
     province:"California",
     city:"LA"},
    {country:"China",
     province:"Sichuan",
     city:"Chengdu"}
 ]
}

Ignoring the details, you just need to know that I've gotten an array of address after resolving the json, however, the address array is declared as Object[], not Address[].

This is because when I was trying to parse json into java bean instance, the only information about the target bean is Student.class.

And you may already guessed that Field.set(arr) would throw a ClassCastException because we cannot set a Object[] into a field which is a Address[].

So finally I decided to use Array.newInstance() to solve the trouble, the code is like this:

Object arr = Array.newInstance(fieldClass.getComponentType(), jsonArray.size());
for (int i = 0; i < jsonArray.size(); i++) {
    // use Array.set() to fill the arr
}
targetField.set(targetObject, arr);
  • PS:

    You may have doubt like: "Why don't you just create an array which is declared as Address[] instead of Object[]"
    Just like what I said: I do not know how to do it when the only information I got is Student.class.

  • Question

    So my question is: Are there any other ways to implement this? Or my solution is already the most common one?

  • Last

    I'd be really grateful if you can tell me a better way, or just give me a brief comment of my solution, so I can improve this JSON-Parser!

Sincerely SCU-Jimmy.





Aucun commentaire:

Enregistrer un commentaire