GSON does not return JSON key - java

I am using GSON to convert objects into JSON. I have this:
String name = "MyName";
and I use the following statement to convert it to json:
print(new Gson().toJson(name));
and the output is : "MyName"
How can I make it print in this way:
{"name":"myName"}

There are two options:
class YourClass {
private String name;
// getters and setters...
}
YourClass object = new YourClass();
object.setName("MyName");
print(new Gson().toJson(object));
And using JsonObject:
JsonObject object = new JsonObject();
object.addProperty("name", "MyName");
print(new Gson().toJson(object);

public class Test {
String name = "myName";
public static void main(String[] args) {
System.out.println(new Gson().toJson(new Test()));
}
}

Related

Convert array of strings in json to normal String array in java

Here is the response from web service:
{"courses":["Bca Graphics","OS","DBMS","dnn"]}
I want to parse the courses array to Java String array? I tried, but I amnot able to find a solution.
Using org.json.JSONObject, you can do something like this:
String jsonStr = "{\"courses\":[\"Bca Graphics\",\"OS\",\"DBMS\",\"dnn\"]}";
JSONArray jsonArray = new JSONObject(jsonStr).getJSONArray("courses");
List<String> strings = jsonArray.toList().stream()
.map(Object::toString)
.collect(Collectors.toList());
You can use Gson here.
String inputJson = "{\"courses\":[\"Bca Graphics\",\"OS\",\"DBMS\",\"dnn\"]}";
Gson gSon = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY).create();
MyPojo myPojo = gSon.fromJson(inputJson, MyPojo.class);
System.out.println(myPojo.getCourses());
POJO
public class MyPojo {
public List<String> courses;
public List<String> getCourses() {
return courses;
}
public void setCourses(List<String> courses) {
this.courses = courses;
}
}

How to generate Json with Java

I am working on an application where i have to generate a json like this:
[
{"title":"Culture","start":"Salary","end":"Work"},
{"title":"Work","start":"Salary","end":"Work"}
]
But my code generates json like this:
{{"name":"Culture"},[{"name":"Salary"},{"name":"Work"}],}
My code:
public class ParseJson {
public static class EntryListContainer {
public List<Entry> children = new ArrayList<Entry>();
public Entry name;
}
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
}
public static void main(String[] args) {
EntryListContainer elc1 = new EntryListContainer();
elc1.name = new Entry("Culture");
elc1.children.add(new Entry("Salary"));
elc1.children.add(new Entry("Work"));
ArrayList<EntryListContainer> al = new ArrayList<EntryListContainer>();
Gson g = new Gson();
al.add(elc1);
StringBuilder sb = new StringBuilder("{");
for (EntryListContainer elc : al) {
sb.append(g.toJson(elc.name));
sb.append(",");
sb.append(g.toJson(elc.children));
sb.append(",");
}
String partialJson = sb.toString();
if (al.size() > 1) {
int c = partialJson.lastIndexOf(",");
partialJson = partialJson.substring(0, c);
}
String finalJson = partialJson + "}";
System.out.println(finalJson);
}
}
Can anyone help me to generate this json in my required format ?? please thanks in advance
Try this
public class Entry {
public String title;
public String start;
public String end;
}
And in another part of your code
private ArrayList<Entry> entries = new ArrayList<>();
// Fill the entries...
String the_json = new Gson().toJson(entries);
1) First Create your POJO
public class MyJSONObject {
private String title;
private String start;
private String end;
//getter and setter methods
[...]
#Override
public String toString() {
}
}
2) Use com.google.code.gson library
public static void main(String[] args) {
{
ArrayList<MyJSONObject> myJSONArray = new ArrayList<>();
MyJSONObject obj = new MyJSONObject();
obj.setTitle="Culture";
obj.set[...]
myJSONArray.add(obj);
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(myJSONArray);
System.out.println(json);
}
Output : [{"title":"Culture","start":"Salary","end":"Work"}, ...]
I recommend you to use some JSON Java API, like Gson. It's very simple to generate a string json from a POJO object or to create a POJO object from a string json.
The code for generating a string json from a POJO object is like this:
Gson gson = new Gson();
String stringJson = gson.toJson(somePojoObject);
The code for creating a POJO object from a string json is like this:
Gson gson = new Gson();
SomePojoClass object = gson.fromJson(stringJson, SomePojoClass.class);
Note that you can not serialize objects with circular references. This causes infinite recursion.

How to convert Map of class<T> objects to json java

I have class with some properties, for example:
public class MyClass {
public int number;
public String s;
}
and I want to convert Map of this class to json. for example:
Map<String, MyClass> map = new HashMap();
map.put("sss", new MyClass(1, "blabla");
json j = new json(map);
and I want the output to be like:
{"sss":{"number":"1","s":"blabla"}}
someone know how to do that in JAVA? I tried with JSONObject and with Gson but did not work for me.
you can use toJson() method of Gson class to convert a java object to json ,see the example below ,
public class SomeObject {
private int data1 = 100;
private String data2 = "hello";
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
//getter and setter methods
#Override
public String toString() {
return "SomeObject [data1=" + data1 + ", data2=" + data2 + ", list="
+ list + "]";
}
}
i will convert the above class' object to json , getter and setter methods are useful when you are converting the json back to java object .
public static void main(String[] args) {
SomeObject obj = new SomeObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
System.out.println(json);
}
output :
{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}
Using Gson:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(map);
You have to fix, parenthesis issue.
map.put("sss", new MyClass(1,"test")); //observe 2 braces at the end!
Following code should do the trick for you,
Gson gson = new Gson();
String myJson = gson.toJson(map);
Output:
{"sss":{"number":1,"s":"test"}}
Implement some custom toJSON() method for each class as shown below:
public class MyClass1 {
String number;
String name;
public MyClass1(String number, String name){
this.number = number;
this.name = name;
}
public JSONObject toJSON() throws JSONException {
return new JSONObject("{\"number\" : \""+this.number+"\", \"name\":\""+this.name+"\"}");
}
}
And then just use it to convert your map to jsonObject:
public class MapToJSON {
public static void main(String[] args) throws JSONException {
Map<String, JSONObject> map = new HashMap<String, JSONObject>();
map.put("sss", new MyClass1("1", "Hello").toJSON());
System.out.println(new JSONObject(map));
}
}
I found the way how to do that:
import com.google.gson.Gson;
import org.json.JSONObject;
Gson gson = new Gson();
map.put("sss", new JSONObject(gson.toJson(new MyClass(1, "Hello"))));
map.put("aaa", new JSONObject(gson.toJson(new MyClass(2, "blabla"))));
String output = new JSONObject(map).toString();
and now the output is correct.
Thanks a lot to all the people that tried to help me with this problem...

gson - include class name when serializing java pojo -> json

Using GSON how do I append the class name of my List to my outputted json string? I've looked through the api and have missed any reference to do this. I'm using GsonBuilder in my real code but don't see any options for it either.
public class Person {
String name;
public Person(String name){
this.name = name;
}
public static void main(String [] args){
Person one = new Person("Alice");
Person two = new Person("Bob");
List<Person> people = new ArrayList<Person>();
people.add(one);
people.add(two);
String json = new Gson(people);
}
}
This gives the following output:
json = [{"name": "Alice"},{"name": "Bob"}]
How do I achieve the following output? or something similar.
json = {"person":[{"name": "Alice"},{"name": "Bob"}]}
or
json = [{"person":{"name": "Alice"}},{"person":{"name": "Bob"}}]
Hope it's something trivial that I have just missed. Thanks in advance.
I don't know if the answer is still interesting you but what you can do is the following:
public static void main(String [] args){
Person one = new Person("Alice");
Person two = new Person("Bob");
List<Person> people = new ArrayList<Person>();
people.add(one);
people.add(two);
Gson gson = new Gson();
JsonElement je = gson.toJsonTree(people);
JsonObject jo = new JsonObject();
jo.add("person", je);
System.out.println(jo.toString()); //prints {"person":[{"name": "Alice"},{"name": "Bob"}]}
}

GSON to deserialise array of name/value pairs

my string is:
"[{"property":"surname","direction":"ASC"}]"
can I get GSON to deserialise this, without adding to it / wrapping it?
Basically, I need to deserialise an array of name-value pairs.
I've tried a few approaches, to no avail.
You basically want to represent it as List of Maps:
public static void main( String[] args )
{
String json = "[{\"property\":\"surname\",\"direction\":\"ASC\"}]";
Type listType = new TypeToken<ArrayList<HashMap<String,String>>>(){}.getType();
Gson gson = new Gson();
ArrayList<Map<String,String>> myList = gson.fromJson(json, listType);
for (Map<String,String> m : myList)
{
System.out.println(m.get("property"));
}
}
Output:
surname
If the objects in your array contain a known set of key/value pairs, you can create a POJO and map to that:
public class App
{
public static void main( String[] args )
{
String json = "[{\"property\":\"surname\",\"direction\":\"ASC\"}]";
Type listType = new TypeToken<ArrayList<Pair>>(){}.getType();
Gson gson = new Gson();
ArrayList<Pair> myList = gson.fromJson(json, listType);
for (Pair p : myList)
{
System.out.println(p.getProperty());
}
}
}
class Pair
{
private String property;
private String direction;
public String getProperty()
{
return property;
}
}

Categories

Resources