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...
Related
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()));
}
}
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.
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);
}
}
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;
}
}
I want to parse JSON arrays and using gson. Firstly, I can log JSON output, server is responsing to client clearly.
Here is my JSON output:
[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]
I tried this structure for parsing. A class, which depends on single array and ArrayList for all JSONArray.
public class PostEntity {
private ArrayList<Post> postList = new ArrayList<Post>();
public List<Post> getPostList() {
return postList;
}
public void setPostList(List<Post> postList) {
this.postList = (ArrayList<Post>)postList;
}
}
Post class:
public class Post {
private String id;
private String title;
/* getters & setters */
}
When I try to use gson no error, no warning and no log:
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
PostEntity postEnt;
JSONObject jsonObj = new JSONObject(jsonOutput);
postEnt = gson.fromJson(jsonObj.toString(), PostEntity.class);
Log.d("postLog", postEnt.getPostList().get(0).getId());
What's wrong, how can I solve?
You can parse the JSONArray directly, don't need to wrap your Post class with PostEntity one more time and don't need new JSONObject().toString() either:
Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);
I was looking for a way to parse object arrays in a more generic way; here is my contribution:
CollectionDeserializer.java:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
#Override
public Collection<?> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
return parseAsArrayList(json, realType);
}
/**
* #param serializedData
* #param type
* #return
*/
#SuppressWarnings("unchecked")
public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
ArrayList<T> newArray = new ArrayList<T>();
Gson gson = new Gson();
JsonArray array= json.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
while(iterator.hasNext()){
JsonElement json2 = (JsonElement)iterator.next();
T object = (T) gson.fromJson(json2, (Class<?>)type);
newArray.add(object);
}
return newArray;
}
}
JSONParsingTest.java:
public class JSONParsingTest {
List<World> worlds;
#Test
public void grantThatDeserializerWorksAndParseObjectArrays(){
String worldAsString = "{\"worlds\": [" +
"{\"name\":\"name1\",\"id\":1}," +
"{\"name\":\"name2\",\"id\":2}," +
"{\"name\":\"name3\",\"id\":3}" +
"]}";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
Gson gson = builder.create();
Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
assertNotNull(decoded);
assertTrue(JSONParsingTest.class.isInstance(decoded));
JSONParsingTest decodedObject = (JSONParsingTest)decoded;
assertEquals(3, decodedObject.worlds.size());
assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
}
}
World.java:
public class World {
private String name;
private Long id;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
To conver in Object Array
Gson gson=new Gson();
ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);
To convert as post type
Gson gson=new Gson();
Post [] refVar=gson.fromJson(jsonString,Post[].class);
To read it as List of objects TypeToken can be used
List<Post> posts=(List<Post>)gson.fromJson(jsonString,
new TypeToken<List<Post>>(){}.getType());
Type listType = new TypeToken<List<Post>>() {}.getType();
List<Post> posts = new Gson().fromJson(jsonOutput.toString(), listType);
Some of the answers of this post are valid, but using TypeToken, the Gson library generates a Tree objects whit unreal types for your application.
To get it I had to read the array and convert one by one the objects inside the array. Of course this method is not the fastest and I don't recommend to use it if you have the array is too big, but it worked for me.
It is necessary to include the Json library in the project. If you are developing on Android, it is included:
/**
* Convert JSON string to a list of objects
* #param sJson String sJson to be converted
* #param tClass Class
* #return List<T> list of objects generated or null if there was an error
*/
public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){
try{
Gson gson = new Gson();
List<T> listObjects = new ArrayList<>();
//read each object of array with Json library
JSONArray jsonArray = new JSONArray(sJson);
for(int i=0; i<jsonArray.length(); i++){
//get the object
JSONObject jsonObject = jsonArray.getJSONObject(i);
//get string of object from Json library to convert it to real object with Gson library
listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
}
//return list with all generated objects
return listObjects;
}catch(Exception e){
e.printStackTrace();
}
//error: return null
return null;
}
You can easily do this in Kotlin using the following code:
val fileData = "your_json_string"
val gson = GsonBuilder().create()
val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()
Basically, you only need to provide an Array of YourClass objects.
[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]
Check Easy code for this output
Gson gson=new GsonBuilder().create();
List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));
in Kotlin :
val jsonArrayString = "['A','B','C']"
val gson = Gson()
val listType: Type = object : TypeToken<List<String?>?>() {}.getType()
val stringList : List<String> = gson.fromJson(
jsonArrayString,
listType)
you can get List value without using Type object.
EvalClassName[] evalClassName;
ArrayList<EvalClassName> list;
evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
list = new ArrayList<>(Arrays.asList(evalClassName));
I have tested it and it is working.