Home » Java » json – How to convert a JSONObject to a Java Bean with string variables?-Exceptionshub

json – How to convert a JSONObject to a Java Bean with string variables?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

How can I convert a JSONObject to a PersonBean as below? I have an intermediary Person with a name field and a List<String for other attributes. The List is of indeterminate size, but less than ten items.

My thinking is to create PersonBean with additional String fields and then manually copy values from the List into bean setters.

But, of course I’m getting out of bound errors when creating a PersonBean because the List might be empty:

package groupBaseX.io;

import java.util.logging.Logger;

public class PersonBeanBuilder {

    private static final Logger log = Logger.getLogger(PersonBeanBuilder.class.getName());
    private Person person = null;
    private PersonBean personBean = new PersonBean();

    private PersonBeanBuilder() {
    }

    public PersonBeanBuilder(Person person) {
        this.person = person;
        log.fine(person.toString());
        log.fine(person.getName());
        personBean.setName(person.getName());

        String a = person.getAttributes().get(0);
        String b = person.getAttributes().get(1);
        String c = person.getAttributes().get(2);
        String d = person.getAttributes().get(3);
        String e = person.getAttributes().get(4);

        personBean.setA(a);
        personBean.setB(b);
        personBean.setC(c);
        personBean.setD(d);
        personBean.setE(e);

    }

    public PersonBean getPersonBean() {
        return personBean;
    }

}

Certainly, I can just use try/catch but is there not a more elegant solution? The above code is very much a kludge.

because the underlying JSON, in a JSONArray, is of indeterminate size. For practical purposes, I’m only interested in the name and the first few attributes for each object below:

[
  {
    "0":"z10",
    "1":"y9",
    "2":"x7",
    "3":"atrib6",
    "name":"alice"
  },
  {
    "0":"home5",
    "1":"cell4",
    "name":"sue"
  },
  {
    "0":"phone3",
    "1":"phone2",
    "2":"phone1",
    "name":"joe"
  },
  {
    "name":"people"
  }
]

Some JSONObject will of course have zero attributes, but certainly less than ten. Just looking to create a Java Bean from the above JSON, which is from BaseX.

How to&Answers:

This is the somewhat reasonable approach I settled on:

package groupBaseX.io;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class PersonBeanBuilder {

    private static final Logger log = Logger.getLogger(PersonBeanBuilder.class.getName());
    private Person person = null;
    private PersonBean personBean = new PersonBean();

    private PersonBeanBuilder() {
    }

    public PersonBeanBuilder(Person person) {
        this.person = person;

    }

    public PersonBean getPersonBean() {
        personBean.setName(person.getName());

        Map<String, AF> map = new HashMap<>();

        AF attributeField = AF.GARBAGE;
        person.getAttributes().forEach((s) -> {
            map.put(s, attributeField.getType(s));
        });

        for (String key : map.keySet()) {
            switch (map.get(key)) {
                case HOME_PHONE:
                    log.fine(AF.HOME_PHONE.toString());
                    personBean.setHomePhone1(key);
                    break;
                default:
                    log.fine(AF.HOME_PHONE.toString());
                    break;
            }
        }
        return personBean;
    }

}

enum:

package groupBaseX.io;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class AttributeParser {

    private static final Logger log = Logger.getLogger(AttributeParser.class.getName());
    private List<String> attributes = new ArrayList<>();

    private AttributeParser() {
    }

    public AttributeParser(List<String> attributes) {
        this.attributes = attributes;
    }

    // ^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$  phone
    // ^\d{5}(?:[-\s]\d{4})?$     zip
    public void foo() {

        boolean isPhone = false;
        boolean isZip = false;
        for (String s : attributes) {
            int x = 3;
            isPhone = false;
            isZip = false;

        }
    }

}

But, still quite awkward. The starting point is JSON so I’m sure this has been figured by smarter monkeys than me already.