How can we get json in below format using XStream or any other parser?

In the below format my doubt is the type mentioned with every field. Can you please suggest some solution? This is a requirement from the third party who will be consuming this.

subject":{ "type":"string", "$":"Cabinet model number?" }

Answers


Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

Below is how this can be done using MOXy's JSON-binding.

Domain Model (Root)

The @XmlElement annotation can be used to specify the type of the property. Setting the type to be Object will force a type qualified to be written out.

import javax.xml.bind.annotation.*;

public class Root {

    private String subject;

    @XmlElement(type=Object.class)
    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

}

Demo

Since a type qualifier will be marshalled out a key will need to be written for the value. By default this will be value. You can use the JSON_VALUE_WRAPPER property to change this to $.

import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(3);
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        properties.put(JAXBContextProperties.JSON_VALUE_WRAPPER, "$");
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Root.class}, properties);

        Root root = new Root();
        root.setSubject("Cabinet model number?");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

Output

Below is the output from running the demo code.

{
   "subject" : {
      "type" : "string",
      "$" : "Cabinet model number?"
   }
}

For More Information


Need Your Help

How do I prompt the user to accept or reject a HTTPS certificate?

java android https

My Android app sends requests to an external HTTP server using the DefaultHttpClient API. I am having trouble switching to HTTPS.

HTML Canvas Full Screen

javascript html5 canvas

I'm playing with the following application using the HTML Canvas: http://driz.co.uk/particles/

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.