November 20, 2017

Rest call to Java Json sample program

Getting JSON Response from Rest Call in java

Description

This is a rest service call in java. The rest service which returns josn as response is saved to Java Object through Object Mapper API. The Object Mapper is very simple to use


/**
 *  Json to Java using Object Mapper
 */
package com.belazy.rest;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author itsection kozhikode
 *
 */
public class JsonMapper {

/**
* @param args
* @throws IOException
* @throws JsonMappingException
* @throws JsonGenerationException
*/
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
// TODO Auto-generated method stub

ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("bmw","blue");
File resultFile = new File("d://belazy.json");
objectMapper.writeValue(resultFile, car);

ComputerDetails comp = objectMapper.readValue(new URL("http://ip.jsontest.com"), ComputerDetails.class);
System.out.println(comp.getIp());

JsonKey jsonkey = objectMapper.readValue(new URL("http://echo.jsontest.com/key/value/one/two"), JsonKey.class);
System.out.println("jsonkey.getOne() : "+jsonkey.getOne());

}





}


computerdetails.class




/**
 *
 */
package com.belazy.rest;

/**
 * @author belazy
 *
 */
public class ComputerDetails {

String ip;

/**
* @return the ip
*/
public String getIp() {
return ip;
}

/**
* @param ip the ip to set
*/
public void setIp(String ip) {
this.ip = ip;
}


}

jsonkey.class


package com.belazy.rest;
public class JsonKey
{
    private String one;

    private String key;

    public String getOne ()
    {
        return one;
    }

    public void setOne (String one)
    {
        this.one = one;
    }

    public String getKey ()
    {
        return key;
    }

    public void setKey (String key)
    {
        this.key = key;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [one = "+one+", key = "+key+"]";
    }
}

java api needed



jackson annotation jar
jackson core
jackson databind



Output



86.99.219.5
jsonkey.getOne()two

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments