JAXB JSON brackets on arrays


I am trying to copy brackets in lists that contain only one item.

I want something like this:
{"id": "0", "industries": [{"id": "0", "name": "Technologies"}], "name": "Google Inc." }

But I get:
{"id": "0", "industries": {"id": "0", "name": "Technologies"}, "name": "Google Inc." }

Here is my essence:

@Entity @XmlRootElement public class Company { private int id; private String name; private String description; @XMLElement(name="industries") private List<Industry> industryList; [...] 

And finally, my JAXB context resolver:

 public JAXBContextResolver() throws Exception { 

MappedBuilder builder = JSONConfiguration.mapped (); builder.arrays ("industry"); builder.rootUnwrapping (true);

this.context = new JSONJAXBContext (builder.build (), Company.class); }

+4
source share
4 answers

Thanks for your help, but I found the answer. You really need to specify JAXBContextResolver which define the natural JSON configuration. You need to provide a list of types for each container that needs to be converted to JSON. In this example, you can see that I specified GetCompanyResponse, which is the container of the company.

 @Provider public class JAXBContextResolver implements ContextResolver<JAXBContext> { private JAXBContext context; private Class[] types = { GetCompanyResponse.class }; public JAXBContextResolver() throws Exception { this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types); } public JAXBContext getContext(Class<?> objectType) { for (Class clazz : types) { if (clazz.equals(objectType)) { return context; } } return null; } } 
+1
source

I'm not too sure about this, but try removing the @XMLElement annotation for the industry list

I did things the other way around: using jaxb to create java classes from xsd schema files. I looked at the generated classes with collection fields, and they have no specific annotations.

You can also try JSON Lib: http://json-lib.sourceforge.net/

you can do things like:

 jsonString = JSONObject.fromObject(pojoObject) 

which will generate a json string that will include, for example, collections of complex types.

Then you can send jsonString using e.g. HttpServletResponse.

I would recommend serializing DTO objects, rather than serializing entity objects.

0
source

Note. I am EclipseLink JAXB (MOXy) and a member of the JAXB 2 group (JSR-222) .

EclipseLink JAXB (MOXy) provides native support for JSON binding. It will correctly marshal collections of size 1 wrapped in a JSON array. The following is a complete example.

Company

 package forum3946102; import java.util.List; import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Company { private int id; private String name; private String description; @XmlElement(name = "industries") private List<Industry> industryList; } 

Industry

 package forum3946102; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class Industry { private int id; private String name; } 

jaxb.properties

To specify MOXy as your JAXB provider, you need to add a file called jaxb.properties in the same package as your domain classes, with the following entry:

 javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory 

Demo

 package forum3946102; import java.io.StringReader; import javax.xml.bind.*; import javax.xml.transform.stream.StreamSource; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Company.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setProperty("eclipselink.media-type", "application/json"); unmarshaller.setProperty("eclipselink.json.include-root", false); String jsonString = "{\"id\":\"0\",\"industries\":[{\"id\":\"0\",\"name\":\"Technologies\"}],\"name\":\"Google Inc.\"}"; StreamSource jsonSource = new StreamSource(new StringReader(jsonString)); Company company = unmarshaller.unmarshal(jsonSource, Company.class).getValue(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty("eclipselink.media-type", "application/json"); marshaller.setProperty("eclipselink.json.include-root", false); marshaller.marshal(company, System.out); } } 

Output

The following is the result of running the demo code:

 {"id" : 0, "name" : "Google Inc.", "industries" : [{"id" : 0, "name" : "Technologies"}]} 

Additional Information

0
source

Expand JSONObject and replace the scope, which should be a JSONArray. After json is created, putOpt will replace the old reference object with the new one.

Before the Investment: {"SubAccount": {"id": "SubAccountId_2_CORP", "AllocPercent": "100.0", "ProductCode": "PC01", "ProductFullName": "Full name of the product"}}

After "Investment": {"SubAccount": [ {"id": "SubAccountId_2_CORP", "AllocPercent": "100.0", "ProductCode": "PC01", "ProductFullName": "Full name of the product"} ] }

  import org.json.JSONArray; import org.json.JSONObject; import org.json.XML; private static int PRETTY_PRINT_INDENT_FACTOR = 4; 

. ,,.

  try { org.json.JSONObject xmlJSONObj = XML.toJSONObject(inBatchTrans.getINPUT_MESSAGE()); try { JSONArray subAcctArray = xmlJSONObj.getJSONObject("TXLife").getJSONObject("TXLifeRequest").getJSONObject("OLifE").getJSONObject("Holding").getJSONObject("Investment").getJSONArray("SubAccount"); // Already JsonArray do nothing } catch (Exception e) { // convert to Array JSONObject subAcctObj = xmlJSONObj.getJSONObject("TXLife").getJSONObject("TXLifeRequest").getJSONObject("OLifE").getJSONObject("Holding").getJSONObject("Investment").getJSONObject("SubAccount"); JSONArray keys = subAcctObj.names(); JSONArray values = subAcctObj.toJSONArray(keys); JSONObject subAccount = new JSONObject(); JSONArray subAccountList = new JSONArray(); int key = keys.length(); for (int i = 0; i < key; i++) { subAccount.put(keys.get(i).toString(), values.get(i)); } subAccountList.put(0, subAccount); xmlJSONObj.getJSONObject("TXLife").getJSONObject("TXLifeRequest").getJSONObject("OLifE").getJSONObject("Holding").getJSONObject("Investment").putOpt("SubAccount", subAccountList); } String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR); System.out.println(jsonPrettyPrintString); } catch (org.json.JSONException je) { System.out.println(je.toString()); } 
0
source

All Articles