4

I have java class like:

public class Sample{
 int foo=5;
 int bar=6;
}

now I want to generate JSON object but without bar field:

{"foo":5}

What is a best way to accomplish that? Should I compose JSON string manually, or can I use some library, or generator?

Panchito91
  • 1,680
  • 3
  • 13
  • 19

3 Answers3

2

Should I compose JSON string manually

Avoid this, it's all to easy to make invalid json this way. Use of a library ensures proper escaping of characters that would otherwise break the output.

Gson ignores transient fields:

public class Sample {
   private int foo = 5;
   private int transient bar = 6;
}

Gson gson = new Gson();

Or you can choose which to include with Expose attribute:

public class Sample {
   @Expose private int foo = 5;
   private int bar = 6;
}

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

Then whichever approach, do this:

String json = gson.toJson(obj);

To get your desired {"foo":5}

Community
  • 1
  • 1
weston
  • 54,145
  • 21
  • 145
  • 203
  • this works great, but what if I want to select the fields at run time? – Mzzzzzz Nov 10 '16 at 16:23
  • @Mzzzzzz this is too wide to answer in comments. Ask a new question, and explain your usage. Put a link here and I'd be happy to look at it. – weston Nov 10 '16 at 16:31
1

You can use the Jackson to solve your problem. Follow the below step -

Step 1 - Make a method which will convert Java object to Json

public class JsonUtils {
    public static String javaToJson(Object o) {
            String jsonString = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.UNWRAP_ROOT_VALUE,true);  
                jsonString = objectMapper.writeValueAsString(o);

            } catch (JsonGenerationException e) {
                logger.error(e);
            } catch (JsonMappingException e) {
                logger.error(e);
            } catch (IOException e) {
                logger.error(e);
            }
            return jsonString;
        }

}

Step 2 Model Class

package com.javamad.model;

import org.codehaus.jackson.annotate.JsonIgnore;



public class Sample{
     int foo=5;
     public int getFoo() {
        return foo;
    }
    public void setFoo(int foo) {
        this.foo = foo;
    }
    @JsonIgnore
    public int getBar() {
        return bar;
    }
    public void setBar(int bar) {
        this.bar = bar;
    }
    int bar=6;
    }

Step 3 Convert your java class to json

Sample sample = new Sample()
JsonUtils.javaToJson(sample);
Nirmal Dhara
  • 2,121
  • 18
  • 27
-1

you can try Gson, JSON library, to convert object to/from json.

these two methods are helpfull:

toJson() – Convert Java object to JSON format

fromJson() – Convert JSON into Java object

Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
Sonu Gupta
  • 347
  • 3
  • 16