I recently started using GSON and i am facing an issue in deserialising this json. The issue is at below json element which contains spaces in field names
{
longDescriptionNonHTML: {
What it is:: " An oil-free, color-tinted moisturizer."
What it does:: " This lightweight foundation can be reapplied as necessary and offers moisturizing, oil-control coverage for sensitive or acne prone skin."
}
{
SKUType: "restricted"
brandName: "Laura Mercier"
brandId: 5809
skuID: "1228139"
availableInStore: 0
topSellerRank: 8297
productName: "Tinted Moisturizer - Oil Free"
shade_description: "Porcelain"
shortDescription: "What it is: An oil-free, color-tinted moisturizer.What it does: This lightweight foundation can be reapplied as necessary and offers moisturizing, oil-control coverage for sensitive or acne prone skin."
size: "1.7 oz"
listPrice: 0
salePrice: 0
image: "http://www.sephora.com/productimages/sku/s1228139-main-hero.jpg"
rating_product: 4.3
online_store: "http://www.sephora.com/tinted-moisturizer-oil-free-P310929?skuId=1228139&lang=en"
imageBrand: "http://www.sephora.com/contentimages/brands/lauramercier/5809_logo_279.png"
productId: "P310929"
formulation: "Liquid"
spf: ""
coverage: "Sheer, Medium"
finish: "Matte, Natural"
ingredients: "Vitamin C"
skintype: "Combination, Normal, Oily"
longDescription: "<b>What it is:</b><br> An oil-free, color-tinted moisturizer.<br><br><b>What it does:</b><br> This lightweight foundation can be reapplied as necessary and offers moisturizing, oil-control coverage for sensitive or acne prone skin."
longDescriptionNonHTML: {
What it is:: " An oil-free, color-tinted moisturizer."
What it does:: " This lightweight foundation can be reapplied as necessary and offers moisturizing, oil-control coverage for sensitive or acne prone skin."
}-
skintone: "2Y03"
longIngredientsDesc: ""
language: "en"
isPrimarySkintone: 1
isDefaultSku: 0
storeonly: 0
}
I wrote below POJO
public class LongDescriptionNonHTML {
#SerializedName("What it is:")
private String whatItIs;
#SerializedName("What it does:")
private String whatItDoes;
public LongDescriptionNonHTML(String a,String b){
whatItDoes=a;
whatItDoes=b;
}
public String getWhatItIs() {
return whatItIs;
}
public void setWhatItIs(String whatItIs) {
this.whatItIs = whatItIs;
}
public String getWhatItDoes() {
return whatItDoes;
}
public void setWhatItDoes(String whatItDoes) {
this.whatItDoes = whatItDoes;
}
}
Also for deserialise it I wrote below code
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonReader reader = new JsonReader(new FileReader(fileName));
LongDescriptionNonHTML obj=gson.fromJson(reader, LongDescriptionNonHTML.class);
System.out.println(obj.getWhatItDoes());
But it is printing null value.
It may be useful for you to convert JSON to POJO Class.
public static <T> T convertJSON2POJOClass(String json, Class<T> type)
{
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
try{
return (T) gson.fromJson(json, type);
} catch (Exception expJSONToClassConvertor) {
baseDAO.getInstance().logAnError("common", baseDAO.getInstance().stackTraceToString(expJSONToClassConvertor));
return null;
}
If what you posted is the actual JSON and your whole actual POJO code then you have a mismatch between your JSON and POJO structure:
You are asking Gson to produce a LongDescriptionNonHTML from your JSON.
But your JSON is not just that - it actually is some other object that contains a LongDescriptionNonHTML as the value for the key longDescriptionNonHTML.
I solved it
public class LongDescriptionNonHTML {
//#SerializedName("What it is:")
private String whatItIs;
//#SerializedName("What it does:")
private String whatItDoes;
public LongDescriptionNonHTML(String a,String b){
whatItDoes=a;
whatItDoes=b;
}
public String getWhatItIs() {
return whatItIs;
}
public void setWhatItIs(String whatItIs) {
this.whatItIs = whatItIs;
}
public String getWhatItDoes() {
return whatItDoes;
}
public void setWhatItDoes(String whatItDoes) {
this.whatItDoes = whatItDoes;
}
Then created a deserializer
public class FooDeserializer implements JsonDeserializer{
#Override
public LongDescriptionNonHTML deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
JsonObject jo = (JsonObject)json;
String a =jo.get("What it is:").getAsString();
String b =jo.get("What it does:").getAsString();
return new LongDescriptionNonHTML(a,b);
}
}
and then finally tested it
public class jsonTest {
#Test
public void testJson() throws FileNotFoundException{
String fileName="/Users/User/Documents/workspace/simulator/book.json";
Gson gson = new GsonBuilder().setPrettyPrinting().registerTypeAdapter(LongDescriptionNonHTML.class, new FooDeserializer()).create();
JsonReader reader = new JsonReader(new FileReader(fileName));
LongDescriptionNonHTML obj=gson.fromJson(reader, LongDescriptionNonHTML.class);
System.out.println(obj.getWhatItDoes());
}
}
Related
I am trying to deserialize a JSON data to a POJO.
The issue is that the list object is coming as a string, and gson gives an IllegalStateExceptioState. How can I parse the string as a list to an ArrayList using gson?
JSON DATA
{
"report_id":1943,
"history_id":3302654,
"project_id":null,
"owner_emails":"[\"abcd#xyz.com\"]",
"message":"Array\n(\n [name] => SOMENAME\n [age] => 36\n [gender] => male\n)\n"
}
POJO:
public class EventData {
private static Gson gson = new Gson();
#SerializedName("report_id")
public String reportID;
#SerializedName("history_id")
public String historyID;
#SerializedName("project_id")
public String projectID;
#SerializedName("owner_emails")
public ArrayList<String> ownerEmails = new ArrayList<String>();
#SerializedName("message")
public String message;
#SerializedName("title")
public String title;
public CrawlerNotifiedEventData(){
this.projectID = "Undefined";
this.reportID = "Undefined";
this.historyID = "Undefined";
this.title = "";
}
public String toJson(boolean base64Encode) throws java.io.UnsupportedEncodingException{
String json = gson.toJson(this, CrawlerNotifiedEventData.class);
if(base64Encode)
return Base64.getEncoder().encodeToString(json.getBytes("UTF8"));
return json;
}
public String toJson() throws java.io.UnsupportedEncodingException{
return this.toJson(false);
}
public static EventData builder(String json){
return gson.fromJson(json, EventData.class);
}
}
Deserialization:
EventData eventData = EventData.builder(json);
While deserializing i get the following error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 252 path $.owner_emails
Boxing structured data in a string where it is unnecessary is a very common design issue across different serialization approaches. Fortunately, Gson can deal with fields like owner_emails (but not message of course).
Merely create a type adapter factory than can create a type adapter for a particular type by substituting the original one and doing a bit of more work. The adapter is supposed to read the payload as string and delegate the string deserialization to the type adapter it substitutes.
public final class JsonStringBoxTypeAdapterFactory
implements TypeAdapterFactory {
private JsonStringBoxTypeAdapterFactory() {
}
#Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
final TypeAdapter<T> adapter = gson.getAdapter(typeToken);
return new TypeAdapter<T>() {
#Override
public void write(final JsonWriter out, final T value) {
throw new UnsupportedOperationException(); // TODO
}
#Override
public T read(final JsonReader in)
throws IOException {
return adapter.fromJson(in.nextString());
}
};
}
}
#AllArgsConstructor
#ToString
#EqualsAndHashCode
final class EventData {
#SerializedName("owner_emails")
#JsonAdapter(JsonStringBoxTypeAdapterFactory.class)
List<String> ownerEmails;
}
The unit test below will be green:
final EventData eventData = gson.fromJson(json, EventData.class);
Assertions.assertEquals(new EventData(ImmutableList.of("abcd#xyz.com")), eventData);
That's it.
"owner_emails" is curently a string as follows
"owner_emails":"[\"abcd#xyz.com\"]"
It should be
"owner_emails": ["abcd#xyz.com"]
to be considered as array. You can manually remove the quotes and parse it.
Or you can parse it using JsonElement in Gson
You can use ObjectMapper from jackson library for this conversion.
Sample code of conversion::
public <T> T mapResource(Object resource, Class<T> clazz) {
try {
return objectMapper.readValue(objectMapper.writeValueAsString(resource), clazz);
} catch (IOException ex) {
throw new Exception();
}
}
Modify the model for a list like::
public class Reportdata{
private List<String> owner_emails = new ArrayList();
#JsonDeserialize(contentAs = CustomClass.class)
private List<CustomClass> customClassList = new ArrayList();
....// setter and getter
}
In addition to this, while creating the ObjectMapper object you can pass or register the module/ your custom module for deserialization in object like below.
objectMapper.setDefaultPropertyInclusion(Include.NON_EMPTY);
objectMapper.disable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
objectMapper.registerModule(new JavaTimeModule());
Imagine if I have the following JSON
{"game":"football", "people":"elevent"}
{"game":"badminton", "people":"two"}
My class as below
class Sport {
String game;
String people;
}
I could do a deserialize of my Json as below
Sport mySport = Gson().fromJson(json, Sport.class);
However, if my JSON is only
{"game":"football"}
{"game":"badminton"}
I would like it to automatically initialize people to "elevent" or "two", pending of the first field. Is there a way to configure my GsonBuilder() to have that achieve automatically during deserialization?
You could create a custom JsonDeserializer:
public class SportDeserializer implements JsonDeserializer<Sport> {
#Override
public Sport deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = (JsonObject) json;
String game = jsonObject.get("game").getAsString();
JsonElement nullablePeople = jsonObject.get("people");
String people = nullablePeople == null ? null : nullablePeople.getAsString();
if (people == null || people.isEmpty()) {
if (game.equals("football")) {
people = "elevent";
}
else if (game.equals("badminton")) {
people = "two";
}
}
Sport sport = new Sport();
sport.game = game;
sport.people = people;
return sport;
}
}
And then use the custom JsonDeserializer:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Sport.class, new SportDeserializer());
Gson gson = gsonBuilder.create();
Sport sport = gson.fromJson(jsonString, Sport.class);
My answer below isn't the best for this question since I simplified the question, and the other answer would suite this better.
But for more complicated scenarios, my answer below would help. It is basically setup a post-processing after the GSon converted.
I finally use Gson convert post-processing.
class Sport implements PostProcessingEnabler.PostProcessable {
String game;
String people;
#Override
public void gsonPostProcess() {
// The below is something simple.
// Could have more complicated scneario.
if (game.equals("football")) {
people = "elevant";
} else if (game.equals("badminton")) {
people = "two";
}
}
}
class PostProcessingEnabler implements TypeAdapterFactory {
public interface PostProcessable {
void gsonPostProcess();
}
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
return new TypeAdapter<T>() {
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}
public T read(JsonReader in) throws IOException {
T obj = delegate.read(in);
if (obj instanceof PostProcessable) {
((PostProcessable) obj).gsonPostProcess();
}
return obj;
}
};
}
}
Tribute goes to https://blog.simplypatrick.com/til/2016/2016-03-02-post-processing-GSON-deserialization/
I'm using retrofit with gson to deserialize my json into realm objects. This works very well for the most part. Trouble arises when dealing with
RealmList(String(or any other basic data type))
Since Realm doesnt support RealmList where E doesnt extend Realm object, I wrapped String in a RealmObject.
public class RealmString extends RealmObject {
private String val;
public String getValue() {
return val;
}
public void setValue(String value) {
this.val = value;
}
}
My realm Object is as below
public class RealmPerson extends RealmObject {
#PrimaryKey
private String userId;
...
private RealmList<RealmString> stringStuff;
private RealmList<SimpleRealmObj> otherStuff;
<setters and getters>
}
SimpleRealmObj works fine as it only has String elements
public class SimpleRealmObj extends RealmObject {
private String foo;
private String bar;
...
}
How can I deserialize stringStuff? I tried using a gson TypeAdapter
public class RealmPersonAdapter extends TypeAdapter<RealmPerson> {
#Override
public void write(JsonWriter out, RealmPerson value) throws IOException {
out.beginObject();
Log.e("DBG " + value.getLastName(), "");
out.endObject();
}
#Override
public RealmPerson read(JsonReader in) throws IOException {
QLRealmPerson rList = new RealmPerson();
in.beginObject();
while (in.hasNext()) {
Log.e("DBG " + in.nextString(), "");
}
in.endObject();
return rList;
}
However I still hit the IllegalStateException
2334-2334/com.qualcomm.qlearn.app E//PersonService.java:71﹕ main com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was NAME at line 1 column 3 path $.
I tried RealmList, RealmString adapter earlier to no avail.
The only workaround I managed to find so far is https://github.com/realm/realm-java/issues/620#issuecomment-66640786
Any better options?
It is better to use JsonSerializer and JsonDeserializer rather than TypeAdapter for your RealmObject, because of 2 reasons:
They allow you to delegate (de)serialization for your RealmObject to the default Gson (de)serializer, which means you don't need to write the boilerplate yourself.
There's a weird bug in Gson 2.3.1 that might cause a StackOverflowError during deserialization (I tried the TypeAdapter approach myself and encountered this bug).
Here's how (replace Tag with your RealmObject class):
(NOTE that context.serialize and context.deserialize below are equivalent to gson.toJson and gson.fromJson, which means we don't need to parse the Tag class ourselves.)
Parser + serializer for RealmList<Tag>:
public class TagRealmListConverter implements JsonSerializer<RealmList<Tag>>,
JsonDeserializer<RealmList<Tag>> {
#Override
public JsonElement serialize(RealmList<Tag> src, Type typeOfSrc,
JsonSerializationContext context) {
JsonArray ja = new JsonArray();
for (Tag tag : src) {
ja.add(context.serialize(tag));
}
return ja;
}
#Override
public RealmList<Tag> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
RealmList<Tag> tags = new RealmList<>();
JsonArray ja = json.getAsJsonArray();
for (JsonElement je : ja) {
tags.add((Tag) context.deserialize(je, Tag.class));
}
return tags;
}
}
Tag class:
#RealmClass
public class Tag extends RealmObject {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Then register your converter class with Gson:
Gson gson = new GsonBuilder()
.registerTypeAdapter(new TypeToken<RealmList<Tag>>() {}.getType(),
new TagRealmListConverter())
.create();
The error message "Expected a string but was NAME" can be solved by retrieving the name of the json object in the JsonReader before the actual json object (which is a String in your case).
You can take a look at the Android documentation for JsonReader. It has detailed explanation and code snippet. You can also take a look at the readMessage method in the sample code snippet in the documentation.
I have modified your read method to what I think it should be. NOTE: I didn't test the code, so there may be some minor errors in it.
#Override
public RealmPerson read(JsonReader in) throws IOException {
RealmPerson rList = new RealmPerson();
in.beginObject();
String name = "";
while (in.hasNext()) {
name = in.nextName();
if (name.equals("userId")) {
String userId = in.nextString();
// update rList here
} else if (name.equals("otherStuff")) {
// since otherStuff is a RealmList of RealmStrings,
// your json data would be an array
// You would need to loop through the array to retrieve
// the json objects
in.beginArray();
while (in.hasNext()) {
// begin each object in the array
in.beginObject();
name = in.nextName();
// the RealmString object has just one property called "value"
// (according to the code snippet in your question)
if (name.equals("val")) {
String val = in.nextString();
// update rList here
} else {
in.skipValue();
}
in.endObject();
}
in.endArray();
} else {
in.skipValue();
}
}
in.endObject();
return rList;
}
Let me know if this helps.
My gson typeAdapter was the culprit.
The above error was seen as I wasnt deserializing the json into RealmPerson correctly, the first field is not a String, hence
in.nextString()
was borking.
I looked at some example code and it hit me, I didnt have to use
in.beginObject() and in.endObject()
to deserialize a String. The below code works.
public class QLRealmStringAdapter extends TypeAdapter<QLRealmString> {
#Override
public void write(JsonWriter out, QLRealmString value) throws IOException {
Log.e("DBG " + value.getValue(), "");
out.value(value.getValue());
}
#Override
public RealmString read(JsonReader in) throws IOException {
RealmString rString = new RealmString();
if (in.hasNext()) {
String nextStr = in.nextString();
System.out.println("DBG " + nextStr);
rString.setValue(nextStr);
}
return rString;
}
}
Hope this helps someone.
i need a jackson serializer and deserializer for the Converting Arraylist to RealmList
I have an JSON array of arrays where none of the elements are named (it's just a pure array)
[
["http://test.com/","rj76-22dk"],
["http://othertest.com/","v287-28n3"]
]
In Java, I'd like to parse this JSON into an array of connectionobjs, where the connectionobj class looks like this:
public static class connectionOptions {
String URL, RESID;
}
I looked through the GSON documentation, but couldn't seem to find anything pertinent to parsing a JSON array into anything other than another Java Array. I want to parse the JSON array into a Java Object, not an array.
Is there a way to do this using Google's GSON?
I don't recommend this at all. You should try to have appropriate JSON that maps correctly to Pojos.
If you can't change your JSON format, you'll need to register a custom TypeAdapter that can do the conversion. Something like
class ConnectionOptionsTypeAdapter extends TypeAdapter<ConnectionOptions> {
#Override
public void write(JsonWriter out, ConnectionOptions value)
throws IOException {
// implement if you need it
}
#Override
public ConnectionOptions read(JsonReader in) throws IOException {
final ConnectionOptions connectionOptions = new ConnectionOptions();
in.beginArray();
connectionOptions.URL = in.nextString();
connectionOptions.RESID = in.nextString();
in.endArray();
return connectionOptions;
}
}
Then just register it
GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(
ConnectionOptions.class, new ConnectionOptionsTypeAdapter());
Gson gson = gsonBuilder.create();
and use it.
Deserialize your JSON as an ConnectionOptions[] or List<ConnectionOptions>.
I've change your class name to ConnectionOptions to follow Java naming conventions.
You should give a customized Deserializer.
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Collection;
public class TestGson {
public static class ConnectionOptions {
String URL, RESID;
#Override
public String toString() {
return "ConnectionOptions{URL='" + URL + "', RESID='" + RESID + "'}";
}
}
private static class ConnOptsDeserializer implements JsonDeserializer<ConnectionOptions> {
#Override
public ConnectionOptions deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
ConnectionOptions connOpts = new TestGson.ConnectionOptions();
JsonArray array = json.getAsJsonArray();
connOpts.URL = array.get(0).getAsString();
connOpts.RESID = array.get(1).getAsString();
return connOpts;
}
}
public static void main(String[] args) {
String json = "[[\"http://test.com/\",\"rj76-22dk\"],\n" +
" [\"http://othertest.com/\",\"v287-28n3\"]]";
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(ConnectionOptions.class, new ConnOptsDeserializer());
Gson gson = gsonb.create();
Type collectionType = new TypeToken<Collection<ConnectionOptions>>(){}.getType();
Collection<ConnectionOptions> connList = gson.fromJson(json, collectionType);
System.out.println("connList = " + connList);
}
}
I want my JSON to look like this:
{
"information": [{
"timestamp": "xxxx",
"feature": "xxxx",
"ean": 1234,
"data": "xxxx"
}, {
"timestamp": "yyy",
"feature": "yyy",
"ean": 12345,
"data": "yyy"
}]
}
Code so far:
import java.util.List;
public class ValueData {
private List<ValueItems> information;
public ValueData(){
}
public List<ValueItems> getInformation() {
return information;
}
public void setInformation(List<ValueItems> information) {
this.information = information;
}
#Override
public String toString() {
return String.format("{information:%s}", information);
}
}
and
public class ValueItems {
private String timestamp;
private String feature;
private int ean;
private String data;
public ValueItems(){
}
public ValueItems(String timestamp, String feature, int ean, String data){
this.timestamp = timestamp;
this.feature = feature;
this.ean = ean;
this.data = data;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
public int getEan() {
return ean;
}
public void setEan(int ean) {
this.ean = ean;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
#Override
public String toString() {
return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data);
}
}
I just missing the part how I can convert the Java object to JSON with Jackson:
public static void main(String[] args) {
// CONVERT THE JAVA OBJECT TO JSON HERE
System.out.println(json);
}
My Question is: Are my classes correct? Which instance do I have to call and how that I can achieve this JSON output?
To convert your object in JSON with Jackson:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
I know this is old (and I am new to java), but I ran into the same problem. And the answers were not as clear to me as a newbie... so I thought I would add what I learned.
I used a third-party library to aid in the endeavor: org.codehaus.jackson
All of the downloads for this can be found here.
For base JSON functionality, you need to add the following jars to your project's libraries:
jackson-mapper-asl
and
jackson-core-asl
Choose the version your project needs. (Typically you can go with the latest stable build).
Once they are imported in to your project's libraries, add the following import lines to your code:
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service
User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "sampleU#example.com";
ObjectMapper mapper = new ObjectMapper();
try {
// convert user object to json string and return it
return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException e) {
// catch various errors
e.printStackTrace();
}
The result should looks like this:
{"firstName":"Sample","lastName":"User","email":"sampleU#example.com"}
Just follow any of these:
For jackson it should work:
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
//will return json in string
For gson it should work:
Gson gson = new Gson();
return Response.ok(gson.toJson(yourClass)).build();
You could do this:
String json = new ObjectMapper().writeValueAsString(yourObjectHere);
This might be useful:
objectMapper.writeValue(new File("c:\\employee.json"), employee);
// display to console
Object json = objectMapper.readValue(
objectMapper.writeValueAsString(employee), Object.class);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(json));
You can use Google Gson like this
UserEntity user = new UserEntity();
user.setUserName("UserName");
user.setUserAge(18);
Gson gson = new Gson();
String jsonStr = gson.toJson(user);
Well, even the accepted answer does not exactly output what op has asked for. It outputs the JSON string but with " characters escaped. So, although might be a little late, I am answering hopeing it will help people! Here is how I do it:
StringWriter writer = new StringWriter();
JsonGenerator jgen = new JsonFactory().createGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(object);
jgen.close();
System.out.println(writer.toString());
Note: To make the most voted solution work, attributes in the POJO have to be public or have a public getter/setter:
By default, Jackson 2 will only work with fields that are either
public, or have a public getter method – serializing an entity that
has all fields private or package private will fail.
Not tested yet, but I believe that this rule also applies for other JSON libs like google Gson.
public class JSONConvector {
public static String toJSON(Object object) throws JSONException, IllegalAccessException {
String str = "";
Class c = object.getClass();
JSONObject jsonObject = new JSONObject();
for (Field field : c.getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
String value = String.valueOf(field.get(object));
jsonObject.put(name, value);
}
System.out.println(jsonObject.toString());
return jsonObject.toString();
}
public static String toJSON(List list ) throws JSONException, IllegalAccessException {
JSONArray jsonArray = new JSONArray();
for (Object i : list) {
String jstr = toJSON(i);
JSONObject jsonObject = new JSONObject(jstr);
jsonArray.put(jsonArray);
}
return jsonArray.toString();
}
}