Don Rhummy
Don Rhummy

Reputation: 25830

How do i unmarshall a JSON response without using moxy but only the Java SDK?

Every example I've seen uses/requires EclipseLink/Moxy to unmarshall a JSON response object. Is there a way to do this with just the Java SDK implementation/runtime?

My code is:

URL url = new URL( uri );
HttpURLConnection connection =( HttpURLConnection ) url.openConnection();
connection.setRequestMethod( "POST" );
connection.setRequestProperty( "Accept", "application/json" );
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
connection.setRequestProperty( "charset", "utf-8");
connection.setDoOutput( true );
connection.setUseCaches(false);
connection.setDoInput(true);

//Create body for request
String body = "user=joe&pass=test";
byte[] outputInBytes = body.getBytes("UTF-8");
connection.setRequestProperty( "Content-Length", Integer.toString( outputInBytes.length ));
DataOutputStream os = new DataOutputStream( connection.getOutputStream() );

//Sent request
os.write( outputInBytes );
os.close();

//Create our unmarshaller
JAXBContext jc = JAXBContext.newInstance( LoginResponse.class );
InputStream json = connection.getInputStream();
Unmarshaller unmarshaller = jc.createUnmarshaller();

//What do I do here?
//unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE,, "application/json");

//This throws an error
//LoginResponse login = ( LoginResponse ) jc.createUnmarshaller().unmarshal( json );

//So does this
LoginResponse login = ( LoginResponse ) unmarshaller.unmarshal( json );
System.out.println( login );

Upvotes: 1

Views: 49

Answers (1)

ulab
ulab

Reputation: 1089

JDK does not have inherent support. You will have to use one of the JSON libraries. Below works good.

GSON
Jackson

Upvotes: 1

Related Questions