Convert JSON String to JSON - json

I am querying Postgres DB for retrieving JSONB format data using spring data JPA, which is stored like this in DB :
"{
"name":"abc",
"place"="xyz"
}"
but I am getting the response back with out double quotes, is there a way that I get the double quotes using spring data JPA or convert back to JSON with double quotes?
I tried new GSON().tJson() and ObjectMapper but no luck any help is appreciated.
Thanks

Your JSON object format is quite good and you should have no issue deserializing it back to a POJO.
Assuming your POJO class is named Template, here down a sample de-serialization implementation:
public class SerializationTest {
private static final String OBJECT = "{\n"
+ "\"name\":\"abc\",\n"+
"\"place\"=\"xyz\"\n"+
"}";
public static void main(String[] args) {
System.out.println("Serialized object:\n" + OBJECT);
Gson gson = new Gson();
Template template = gson.fromJson(OBJECT, Template.class);
System.out.println(template);
}
private static class Template {
private String name;
private String place;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
#Override
public String toString() {
return "Template{" +
"name='" + name + '\'' +
", place='" + place + '\'' +
'}';
}
}
}

Related

jackson - avoid serializing getters

I have a class that has some additional getters for derived values. When I serialize this with jackson objectmapper, it writes out that field as well. Is there a way to avoid that?
example -
public class CustomPath implements Serializable {
private String path;
private String name;
private String extension = ".txt";
#JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public CustomPath(#JsonProperty("path") String path, #JsonProperty("name") String name) {
this.path = path;
this.name = name;
}
public String getPath()
{ return this.path;}
public void setPath(String path)
{ this.path = path;}
public String getName()
{ return this.name;}
public void setName(String name)
{ this.name = name;}
public String getExtension()
{ return this.extension;}
public void setExtension(String extension)
{ this.extension = extension;}
public String getFullPath() //do not want to serialize this
{ return this.path +"/" + this.name + this.extension;}
}
The json for a class like this looks like -
{
path: somepath
name: somename
extension: .txt
fullPath: somepath/somename.txt
}
But I do not want to serialize 'fullPath' in the example above. Is there any way I can avoid that?
You need to annotate the getFullPath() method with #JsonIgnore:
#JsonIgnore
public String getFullPath() // do not want to serialize this
{
return this.path + "/" + this.name + this.extension;
}
Then the JSON output will look like this:
{
"path" : "somePath",
"name" : "someName",
"extension" : ".txt"
}

JAX-RS/Jackson -- Deserialize JSON with Unknown Root Element Name?

I am writing a RESTeasy Proxy Client to consume Apple's API for retrieving their iTunes category list. When you query for information about a given category , for example with this URL:
https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/genres?id=1420
...you get a JSON response that looks like this:
{
"1420":{
"name":"Self-Help",
"id":"1420",
"url":"https://itunes.apple.com/us/genre/podcasts-health-self-help/id1420?mt=2",
"rssUrls":{
"topVideoPodcastEpisodes":"https://itunes.apple.com/us/rss/topvideopodcastepisodes/genre=1420/json",
"topAudioPodcasts":"https://itunes.apple.com/us/rss/topaudiopodcasts/genre=1420/json",
"topVideoPodcasts":"https://itunes.apple.com/us/rss/topvideopodcasts/genre=1420/json",
"topPodcasts":"https://itunes.apple.com/us/rss/toppodcasts/genre=1420/json",
"topAudioPodcastEpisodes":"https://itunes.apple.com/us/rss/topaudiopodcastepisodes/genre=1420/json",
"topPodcastEpisodes":"https://itunes.apple.com/us/rss/toppodcastepisodes/genre=1420/json"
},
"chartUrls":{
"videoPodcastEpisodes":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=VideoPodcastEpisodes",
"podcasts":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=Podcasts",
"audioPodcastEpisodes":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=AudioPodcastEpisodes",
"audioPodcasts":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=AudioPodcasts",
"podcastEpisodes":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=PodcastEpisodes",
"videoPodcasts":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=VideoPodcasts"
}
}
}
I am trying to map this JSON response to a Java object using JAXB and Jackson. However, the "1420" root element name seems to be causing a problem, as I get the following exception when calling my client:
Unrecognized field "1420" (class foo.bar.ITunesCategoryList), not marked as ignorable
My JAXB class looks like this:
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class ITunesCategory implements TransferObject {
private static final long serialVersionUID = 3443545925023804457L;
#XmlElement(name = "id")
#JsonProperty("id")
private String identifier = null;
#XmlElement
private String name = null;
#XmlElementWrapper(name = "subgenres")
private List<ITunesCategory> subcategories = new ArrayList<ITunesCategory>();
...
}
I've even tried creating a wrapper class since the search could result in more than one category being returned. It looks like this:
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class ITunesCategoryList implements TransferObject {
private static final long serialVersionUID = 3303125979016445238L;
#XmlElement
private List<ITunesCategory> categories = new ArrayList<ITunesCategory>();
...
}
However, regardless of which class I specify as my return type, I get the same error because the category identifier is the root element name of the JSON object.
Is there any way to tell JAXB/Jackson/JAX-RS/RESTeasy to ignore the root element name and just map the underlying object to Java? There is no way for me to know the root element name at develop/compile time, since it corresponds directly to the results returned by the search. Is there anything that can be done to get around this exception? Thanks for any help you can give!
I couldn't find much on dynamically ignoring the root, at least not anything that would be suitable in a JAX-RS environment. The only thing I could think is to write a custom deserializer, and just skip the root node. Something like
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
public abstract class IHateRootElemsJsonDeserializer<T> extends JsonDeserializer<T> {
private final ObjectMapper mapper = new ObjectMapper();
private final Class<T> cls;
public IHateRootElemsJsonDeserializer(Class<T> cls) {
this.cls = cls;
}
#Override
public T deserialize(JsonParser jp, DeserializationContext dc)
throws IOException, JsonProcessingException {
JsonNode rootNode = jp.getCodec().readTree(jp);
Map.Entry<String,JsonNode> field = rootNode.fields().next();
JsonNode node = field.getValue();
T result = mapper.convertValue(node, cls);
return result;
}
}
Then just extend it with a concrete type.
public class GenreDeserializer extends IHateRootElemsJsonDeserializer<Genre>{
public GenreDeserializer() {
super(Genre.class);
}
}
Here's a test using the exact JSON you provided above
public class Test {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
GenreDeserializer deserializer = new GenreDeserializer();
SimpleModule module = new SimpleModule();
module.addDeserializer(Genre.class, deserializer);
mapper.registerModule(module);
Genre genre = mapper.readValue(JSON_FILE, Genre.class);
System.out.println(genre);
genre = mapper.readValue(JSON_FILE, Genre.class);
System.out.println(genre);
}
static final File JSON_FILE = new File("json.json");
}
The model
public class Genre {
public String id;
public String name;
public String url;
public RssUrls rssUrls;
public ChartUrls chartUrls;
#Override
public String toString() {
return "Category{" + "id=" + id + ", name="
+ name + ", url=" + url + ", rssUrls=" + rssUrls + '}';
}
public static class RssUrls {
public String topVideoPodcastEpisodes;
public String topAudioPodcasts;
public String topVideoPodcasts;
public String topPodcasts;
public String topAudioPodcastEpisodes;
public String topPodcastEpisodes;
#Override
public String toString() {
return "RssUrls{" + "topVideoPodcastEpisodes=" + topVideoPodcastEpisodes
+ ", topAudioPodcasts=" + topAudioPodcasts
+ ", topVideoPodcasts=" + topVideoPodcasts
+ ", topPodcasts=" + topPodcasts
+ ", topAudioPodcastEpisodes=" + topAudioPodcastEpisodes
+ ", topPodcastEpisodes=" + topPodcastEpisodes + '}';
}
}
public static class ChartUrls {
public String videoPodcastEpisodes;
public String podcasts;
public String audioPodcastEpisodes;
public String audioPodcasts;
public String podcastEpisodes;
public String videoPodcasts;
#Override
public String toString() {
return "ChatUrls{" + "videoPodcastEpisodes=" + videoPodcastEpisodes
+ ", podcasts=" + podcasts
+ ", audioPodcastEpisodes=" + audioPodcastEpisodes
+ ", audioPodcasts=" + audioPodcasts
+ ", podcastEpisodes=" + podcastEpisodes
+ ", videoPodcasts=" + videoPodcasts + '}';
}
}
}
To configure the ObjectMapper in JAX-RS, you can have a look at this post

json deserialize field of internal object with jackson using data binding

I have a json like this
{
"name": "john",
"photo_urls":
{
"large": "http://www.server.com/john_photo.jpg"
}
}
and I would like to deserialize it in one class, like this
public class Person
{
String name;
String photoUrl;
}
instead of this
public class Person
{
String name;
public class photo_urls
{
String large;
}
}
Is it possible to do it with Jackson using Data Binding and the annotation #JsonProperty? Or is it necessary to use the streaming API instead?
Thanks for your help.
You can consider to have a setter method or a constructor parameter of the Map<String,String> type from which you can get the url field value. Here is an example:
public class JacksonDeserialize {
private static final String JSON = "{\n" +
" \"name\": \"john\",\n" +
" \"photo_urls\":\n" +
" {\n" +
" \"large\": \"http://www.server.com/john_photo.jpg\"\n" +
" }\n" +
"}";
public static class Person
{
private String name;
private String photoUrl;
#JsonCreator
public Person(#JsonProperty("name") String name, #JsonProperty("photo_urls") Map<String, String> photoUrl) {
this.name = name;
this.photoUrl = photoUrl.get("large");
}
#Override
public String toString() {
return "Person{" +
"photoUrl='" + photoUrl + '\'' +
", name='" + name + '\'' +
'}';
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(JSON, Person.class));
}
}
Output:
Person{photoUrl='http://www.server.com/john_photo.jpg', name='john'}

How to convert array s from JSON file to java object

I have a JSON file with two different arrays. I need to convert it into java objects. Is there any method to do it using GSON and JSON. This is what we have tried.
package package1;
import org.json.JSONArray;
import org.json.JSONObject;
public class foo
{
public static void main(String[] args) throws Exception
{
String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";
JSONObject outerObject = new JSONObject(jsonInput);
JSONObject innerObject = outerObject.getJSONObject("JObjects");
JSONArray jsonArray = innerObject.getJSONArray("JArray1");
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
String[] elementNames = JSONObject.getNames(objectInArray);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
for (String elementName : elementNames)
{
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
System.out.println();
}
}
}
PLease guide me with the code.
You can easily parse json objects to java objects and and vice-versa. To do so, you can use Google's framework 'gson': http://code.google.com/p/google-gson/
Maven dependency
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
EXAMPLE:
We make a java model class 'Person'. That person has a first name and a last name:
public class Person {
private String firstname;
private String lastname;
//getters and setters
...
public String toString() {
return "Person [firstname: "+ firstname + ", lastname: " + lastname + "]";
}
}
Now we can create a person object and parse it to a json string with gson:
public class PersonToJson {
public static void main(String[] args) {
Person person = new Person();
person.setFirstname("Laurent");
person.setLastname("Hinoul");
String json = gson.toJson(person);
System.out.println(json);
}
}
The output will be: {"firstname":"Laurent","lastname":"Hinoul"}
Now we can easily parse that string back to an object:
public class JsonToPerson {
public static void main(String[] args) {
final String json = "{"firstname":"Laurent","lastname":"Hinoul"}";
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
System.out.println(person);
}
}
The output will be: Person [firstname: Laurent, lastname: Hinoul]

Render value without quotes from simple-json Object

I try to do in a Servlet:
JSONObject json = new JSONObject();
json.put( "eventContent", "event" );
String script = "var object= " + json.toJSONString() + ";";
response.getWriter().print( something + script + another );
The content of script is of course:
var object = {"eventContent":"event"};
But I render this String into a javascript function and try to refer a existent javascript object "event". So I need the value in the JSON Sting without quotes.
var object = {"eventContent":event};
any suggestions? :)
thanks a lot
I think it's not really JSON, since you should not refer variables. Anyway you can obtain what you need by implementing the JSONString interface, like this.
public static void main(String[] args) throws JSONException {
JSONObject json = new JSONObject();
json.put( "eventContent", new JSONVariable("event") );
System.out.println("var object= " + json.toString() + ";");
}
private static class JSONVariable implements JSONString { // implements JSONAware with com.googlecode.json-simple
private final String name;
public JSONVariable(String name) {
this.name = name;
}
#Override
public String toJSONString() {
return name;
}
}