November 20, 2017

Rest call to Java Json sample program



/**
 *  dedicated to deepa consumerfed
 */
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 nijesh
 *
 */
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


Facebook comments