This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 8 years ago.
I get a json string in server side as follow
[ {"projectFileId":"8547",
"projectId":"8235",
"fileName":"1",
"application":"Excel",
"complexity":"NORMAL",
"pageCount":"2",
"targetLanguages":" ar-SA",
"Id":"8547"
},
{"projectFileId":"8450",
"projectId":"8235",
"fileName":"Capacity Calculator.pptx",
"application":"Powerpoint",
"complexity":"NORMAL",
"pageCount":"100",
"targetLanguages":" ar-LB, ar-SA",
"Id":"8450"
}
]
I want to convert this string into an arraylist or map whichever possible so that I can iterate over it and get the field values.
You can use GSON library. Simply use Gson#fromJson() method to convert JSON string into Java Object.
sample code:
BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Map<String, String>>>() {}.getType();
ArrayList<Map<String, String>> data = gson.fromJson(reader, type);
// convert back to JSON string from object
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
You can create a POJO class to convert it directly into List of POJO clas object to access it easily.
sample code:
class PojectDetail{
private String projectFileId;
private String projectId;
private String fileName;
private String application;
private String complexity;
private String pageCount;
private String targetLanguages;
private String Id;
// getter & setter
}
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<PojectDetail>>() {}.getType();
ArrayList<PojectDetail> data = gson.fromJson(reader, type);
Related
I'm trying to covert Java object to json using Gson library, but its not working as expected and returning empty string,
my code:
String ie = new String("Jack");
Gson gson = new Gson();
String intentcalue = gson.toJson(ie);
it returns:
{}
Please let me know if anything wrong with library, I tried with other Objects as well all returning null value like for Intent Object, ApplicationInfo etc
If you want convert string to json object, your string must be json as well.
For example:
String ie = new String("{\"name\": \"Jack\"}");
Gson gson = new Gson();
String intentcalue = gson.toJson(ie);
I have the following code:
public static void postHttpStream(ArrayListMultimap<String, String> fcmbuildProperties){
HttpClient client = new HttpClient();
Gson gson = new Gson();
System.out.println(fcmbuildProperties);
String jsonString = gson.toJson(fcmbuildProperties);
System.out.println(jsonString);
}
where fcmbuildProperties is an ArrayListMultimap. I try to convert that to JSON here: String jsonString = gson.toJson(fcmbuildProperties); But this returns an empty array. What do I need to do instead?
This is the input that fcmbuildProperties contain : {build.name=[test_project], build.timestamp=[1425600727488], build.number=[121]}
I need to convert this to Json. with key/values.
Use ArrayListMultimap#asMap()
String jsonString = gson.toJson(fcmbuildProperties.asMap());
Gson considers ArrayListMultimap as a Map and ignores its internal state which actually manages the multimap. asMap returns a corresponding Map instance which you can serialize as expected.
This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 8 years ago.
I get a json string in server side as follow
[ {"projectFileId":"8547",
"projectId":"8235",
"fileName":"1",
"application":"Excel",
"complexity":"NORMAL",
"pageCount":"2",
"targetLanguages":" ar-SA",
"Id":"8547"
},
{"projectFileId":"8450",
"projectId":"8235",
"fileName":"Capacity Calculator.pptx",
"application":"Powerpoint",
"complexity":"NORMAL",
"pageCount":"100",
"targetLanguages":" ar-LB, ar-SA",
"Id":"8450"
}
]
I want to convert this string into an arraylist or map whichever possible so that I can iterate over it and get the field values.
You can use GSON library. Simply use Gson#fromJson() method to convert JSON string into Java Object.
sample code:
BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Map<String, String>>>() {}.getType();
ArrayList<Map<String, String>> data = gson.fromJson(reader, type);
// convert back to JSON string from object
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
You can create a POJO class to convert it directly into List of POJO clas object to access it easily.
sample code:
class PojectDetail{
private String projectFileId;
private String projectId;
private String fileName;
private String application;
private String complexity;
private String pageCount;
private String targetLanguages;
private String Id;
// getter & setter
}
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<PojectDetail>>() {}.getType();
ArrayList<PojectDetail> data = gson.fromJson(reader, type);
This question already has answers here:
Java JSON serialization - best practice
(3 answers)
Closed 9 years ago.
I have a list of user objects in a Collection, but I want to convert this into JSON format so that on my html page I can read that json data by using javascript.
List<UserWithEmbeddedContact> users=(List<UserWithEmbeddedContact>) q.execute();
if(!users.isEmpty()) {
for(UserWithEmbeddedContact user:users) {
System.out.println("username="+user.getUsername()+
" password="+user.getPassword()+" mobile="+user.getMobile());
}
}
GSON is your answer:
From their wiki:
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
Ex:
List<UserWithEmbeddedContact> users = (List<UserWithEmbeddedContact>) q.execute();
final Type listType = new TypeToken<List<UserWithEmbeddedContact>>(){}.getType();
final String json = new Gson().toJson(users, listType);
Use json-lib for Java. It's very easy.
try this, it will convert java instance variables into JSON
import com.google.gson.Gson;
public class ObjectToJSON {
// declaring variables to be converted into JSON
private int data1 = 100;
private String data2 = "hello";
private String[] details = { "IBM", "pune", "ind", "12345" };
public static void main(String[] args) {
// Creating the class object
ObjectToJSON obj = new ObjectToJSON();
// Creating Gson class object
Gson gson = new Gson();
// convert java object to JSON format and receiving the JSON String
String json = gson.toJson(obj);
System.out.println(json);
}
}
I know that JSON object is nothing but the String.
My question is that I have a Map of Object and i want to convert it into Json format.
Example :
Java Class ->
Class Person{
private String name;
private String password;
private int number;
}
Java list ->
Map<List<Long>,List<Person>> map=new HashMap<List<Long>,List<Person>>();
..and map has Some data filled in it.
I want to convert that list into
Json Format?
How I can achieve it? Because i want to send it over HttpClient...
If not what is the other alternative way?
As per my knowledge there is Gson API available, but I dont know how to use it and or in other efficient way.
Thank you
Not sure what the problem with Gson is. From the doc:
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
and
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
That object is (as the name suggests) made up of primitives. However Gson will trivially handle objects, collections of objects etc. Life gets a little more complex when using generics etc., but for your example above I would expect Gson to work with little trouble.
Using Gson to convert to Json using Gson at client side.
Sending String array.
String[] subscriberArray = new String[]{"eee", "bbb"};
Gson gson = new Gson();
String recipientInfoStringFormat = gson.toJson(subscriberArray);
Sending Array of User Defined Type.
RecipientInfo[] recipientInfos = new RecipientInfo[1];
RecipientInfo ri = new RecipientInfo();
ri.setA(1);
ri.setB("ss");
recipientInfos.add(ri);
Gson gson = new Gson();
String recipientInfoStringFormat = gson.toJson(recipientInfos);
Using Gson at Server Side to read Data.
For Primitive Types.
String subscriberArrayParam = req.getParameter("subscriberArrayParam");
Gson gson = new Gson();
String[] subscriberArray = gson.fromJson(subscriberArrayParam, String[].class);
for (String str : subscriberArray) {
System.out.println("qq :"+str);
}
For User Defined Object
String recipientInfos = req.getParameter("recipientInfoStringFormat");
Gson gson = new Gson();
RecipientInfo[] ri = gson.fromJson(recipientInfos, RecipientInfo[].class);
You can use jackson also.
Person person= new Person();
ObjectMapper mapper = new ObjectMapper();
try {
// convert personobject to json string, and save to a file
mapper.writeValue(new File("c:\\person.json"), person);
// display to console
System.out.println(mapper.writeValueAsString(person));
} catch (Exception e) {
e.printStackTrace();
}
and vice versa
ObjectMapper mapper = new ObjectMapper();
try {
// read from file, convert it to user class
Person person= mapper.readValue(new File("c:\\person.json"), Person.class);
// display to console
System.out.println(person);
} catch (Exception e) {
e.printStackTrace();
}
for using jackson add this dependency to your POM.xml
<repositories>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/org/codehaus</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
</dependencies>
I got my Answer but Thank you for Your Responses.
Map<Long,List<Person>> map=new HashMap<Long,List<Person>>();
//adding some data
Gson gson=new Gson();
String mapJsonStr=gson.toJson(map);
//mapJsonStr : is my map's JSon Strin
for reverse
TypeToken<Map<Long,List<Person>>> token = new TypeToken<Map<Long,List<Person>>>(){};
Map<Long,List<Person>> map_new=new HashMap<Long,List<Person>>();
map_new=gson.fromJson(mapJsonStr,token.getType());
//origian map
// map_new is my Map get from map's Json String
That's It.Thank you