convert arrayList multimap to json string? - java

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.

Related

Android: gson.toJson converter giving empty string for Android objects

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);

Getting JSON objects / arrays using GSON library without converting to pojos

I used jackson to convert json strings to json objects / arrays like so:
JSONObject jsonObj = XML.toJSONObject(myXmlString);
JSONObject userObj = jsonObj.getJSONObject("user"); // is there a GSON version of this?
JSONArray orders = userObj.getJSONArray("orders");
My main question is: is there a GSON version of getting json objects / arrays without converting to a pojo? My json is very complex so it's difficult to create pojos.
Secondly, does gson allow you to convert an xml string to json like jackson does (line 1)?
For the first question:
You can create a JsonObject from a json string
String json = "{ \"key1\": \"value1\", \"key2\": false}";
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
otherwise you can create a Map object
String jsonString = "{'employee.name':'Bob','employee.salary':10000}";
Gson gson = new Gson();
Map map = gson.fromJson(jsonString, Map.class);
for reference: https://www.baeldung.com/gson-json-to-map
For the second question:
I found this question in stackoverflow
is there a GSON version of getting json objects / arrays without
converting to a pojo?
Something like this can do the job
import com.google.gson.*;
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(myJsonString);
//get as object
JsonObject obj = json.getAsJsonObject();
//get as array
JsonArray arr = json.getAsJsonArray();
does gson allow you to convert an xml string to json like jackson does
No

how to convert Arraylist<myClass> in JSONArray

I'm trying to convert Generic ArrayList in JSONArray but it is displaying null value.
but this is working fine if i'm trying to display specific value from ArrayList.
ArrayList<myClass> experience = new ArrayList<>();
... //adding some values
Log.v("testing", experience.get(0).company); //this is showing value
JSONArray json = new JSONArray(experience);
Log.v("testing", json.toString()); //this is showing [null]
There might be a problem recognizing andn converting your "myClass" bean to json.
Try using gson library to create json and to parse it back to object .
Can use GSON library like this:
Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();
Replace with Below Code and try it will work.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(experience);
Log.e("Jason Array", json);

Convert Java Object to Json and Vice versa?

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

Java convert ArrayList to string and back to ArrayList?

I wanted to save an ArrayList to SharedPreferences so I need to turn it into a string and back, this is what I am doing:
// Save to shared preferences
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("myAppsArr", myAppsArr.toString());
editor.commit();
I can retrieve it with String arrayString = sharedPref.getString("yourKey", null); but I don't know how to convert arrayString back into an ArrayList. How can it be done?
My array looks something like:
[item1,item2,item3]
You have 2 choices :
Manually parse the string and recreate the arraylist. This would be pretty tedious.
Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,
// How to store JSON string
Gson gson = new Gson();
// This can be any object. Does not have to be an arraylist.
String json = gson.toJson(myAppsArr);
// How to retrieve your Java object back from the string
Gson gson = new Gson();
DataObject obj = gson.fromJson(arrayString, ArrayList.class);
Try this
ArrayList<String> array = Arrays.asList(arrayString.split(","))
This will work if comma is used as separator and none of the items have it.
The page http://mjiayou.com/2015/07/22/exception-gson-internal-cannot-be-cast-to/ contains the following:
Type type = new TypeToken<List<T>>(){}.getType();
List<T> list = gson.fromJson(jsonString, type)
perhaps it will be helpful.
//arraylist convert into String using Gson
Gson gson = new Gson();
String data = gson.toJson(myArrayList);
Log.e(TAG, "json:" + gson);
//String to ArrayList
Gson gson = new Gson();
arrayList=gson.fromJson(data, new TypeToken<List<Friends>>()
{}.getType());
I ended up using:
ArrayList<String> appList = new ArrayList<String>(Arrays.asList(appsString.split("\\s*,\\s*")));
This doesn't work for all array types though. This option differs from:
ArrayList<String> array = Arrays.asList(arrayString.split(","));
on that the second option creates an inmutable array.
Update to Dhruv Gairola's answer for Kotlin
val gson = Gson();
val jsonString = gson.toJson(arrayList)

Categories