I have the list
Gson gson = new Gson();
List<String> exampleList = new ArrayList<String>();
exampleList.add("aaa");
exampleList.add("bbb");
exampleList.add("ccc");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("test", gson.toJson(exampleList));
And jsonObject is {"test":"[\"aaa\",\"bbb\",\"ccc\"]"}
but i need get following
{"test":["aaa","bbb","ccc"]}
What the way to do this?
replaceAll in several ways is not solving this problem
You're adding a key-value mapping String -> String, that is why the quotes are escaped (in fact your value is the string representation of the list given by the toString() method). If you want a mapping String -> Array, you need to convert the list as a JsonArray and add it as a property.
jsonObject.add("test", gson.toJsonTree(exampleList, new TypeToken<List<String>>(){}.getType()));
Don't mix Gson and JsonObject,
1) if you need {"test":["aaa","bbb","ccc"]} using GSON you should define
public class MyJsonContainer {
List<String> test = new ArrayList<String>();
...
// getter and setter
}
and use
List<String> exampleList = new ArrayList<String>();
exampleList.add("aaa");
exampleList.add("bbb");
exampleList.add("ccc");
MyJsonContainer jsonContainer = new MyJsonContainer();
jsonContainer.setTest(exampleList);
String json = gson.toJson(jsonContainer); // this json has {"test":["aaa","bbb","ccc"]}
2) if you need {"test":["aaa","bbb","ccc"]} using JsonObject you should just add
List<String> exampleList = new ArrayList<String>();
exampleList.add("aaa");
exampleList.add("bbb");
exampleList.add("ccc");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("test", exampleList);
But never try to mix Gson and JsonObject, because jsonObject.addProperty("test", text) does not allowed to add text as json and allways escaped this text.
String jsonFormattedString = jsonStr.replaceAll("\\\\", "");
Use this for remove \ from string of object.
Related
com.amazonaws.util.json.JSONObject
Below is the List, i want to convert it into json string.
List<JSONObject> jsonObjlist is
[{"Attribute":"EmailAddress","Value":"abc#yahoo.com"}, {"Attribute":"Source","Value":"Missing_Fixed"}, {"Attribute":"mx_Lead_Status","Value":"Registered User"}, {"Attribute":"mx_Age","Value":""}, {"Attribute":"mx_LoginID","Value":"abc#yahoo.com"}, {"Attribute":"mx_Registration_Source","Value":"EMAIL"}]
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String arrayToJson = objectMapper.writeValueAsString(jsonObjlist);
Output i get is
[{"map":{"Attribute":"EmailAddress","Value":"abc#yahoo.com"}},{"map":{"Attribute":"Source","Value":"Missing_Fixed"}},{"map":{"Attribute":"mx_Lead_Status","Value":"Registered User"}},{"map":{"Attribute":"mx_Age","Value":""}},{"map":{"Attribute":"mx_LoginID","Value":"abc#yahoo.com"}},{"map":{"Attribute":"mx_Registration_Source","Value":"EMAIL"}}]
Desired out put is
"[{"Attribute":"EmailAddress","Value":"abc#yahoo.com"}, {"Attribute":"Source","Value":"Missing_Fixed"}, {"Attribute":"mx_Lead_Status","Value":"Registered User"}, {"Attribute":"mx_Age","Value":""}, {"Attribute":"mx_LoginID","Value":"abc#yahoo.com"}, {"Attribute":"mx_Registration_Source","Value":"EMAIL"}]"
You should convert your list to a JSON Array, and just use its toString() function:
JSONArray myArray = new JSONArray(jsonObjlist);
// ...
String arrayToJson = myArray.toString(2);
The int parameter specifies the indent factor to use for formatting.
You can also direct use
String jsonString = new ObjectMapper().writeValueAsString(jsonObjectList)
To get the desired ouptput
Here is the small example
List<JSONObject> jsons = new ArrayList<>();
jsons.add(new JSONObject(ImmutableMap.of("Attribute", "EmailAddress", "Value", "abc#yahoo.com")));
jsons.add(new JSONObject(ImmutableMap.of("Attribute1", "EmailAddress3", "Value1", "abc#yahoo.com1")));
System.out.println(new ObjectMapper().writeValueAsString(jsons));
The output is
[{"Value":"abc#yahoo.com","Attribute":"EmailAddress"},{"Attribute1":"EmailAddress3","Value1":"abc#yahoo.com1"}]
I suspect there are some toString() method in any object that you have override?
We have a requirement to update the JSON data in middle and need to return the updated JSON data using java. Also it should support any type of JSON data.
ex:
Assume {object:{"color":"red","shape":"Triangle"}} is the JSON data and in this we need to update the shape value to Rectangle and we need to return the updated JSON data as below:
{object:{"color":"red","shape":"Rectangle"}}
For this we need to pass the element path ( which element we need to update) and updateText and JSON Data to the JAVA code.
here is the methodCall:
updateValue("object/shape", "Rectangle", "{object:{"color":"red","shape":"Triangle"}}")
We tried below code using Gson library. But with this code we are able to update the targeted Json element, but the requirement is to return the entire JSON data with the updated value.
So please suggest how do we re-build the JSON data with the updated text.
Below is the code we tried to update the Json Data.
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
String result = "";
for(String key : keys)
{
if (jsonObject.get(key) instanceof JsonObject)
{
jsonObject = (JsonObject)jsonObject.get(key);
}
else if(jsonObject.get(key) instanceof JsonArray)
{
JsonArray jsonArray = (JsonArray)jsonObject.get(key);
result = jsonArray.toString();
}
else
{
result = jsonObject.get(key).toString();
}
}
result = result.replace(result, updateText);
return result;
}
The problem lies in the way you do the replacements. When you translate the JsonObject to String, you lose the object, and after replacement, you just have the replaced String. To fix it, you need to operate directly on the object, instead of the String counterpart. Because JsonObject is mutable, holding a reference to the input will reflect the changes. One drawback is you can't replace a value in a JsonArray this way, partly because you don't know which element to replace. To accomplish that, you will need a little more in the input(either the value to replace or the element position).
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
JsonObject returnVal = jsonObject; // This holds the ref to target json object
JsonPrimitive jp = new JsonPrimitive(updateText);
String finalKey = keys[keys.length - 1];
for(String key : keys)
{
if (jsonObject.get(key).isJsonObject())
{
jsonObject = (JsonObject)jsonObject.get(key);
}
}
jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();
}
You can use JsonPath lib for that and try using the following code.
private static final Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
JsonNode updatedJson = JsonPath.using(configuration).parse(originaljson)
.set("use the path to go for value", "new value").json();
json = updatedJson.toString();
Here, I have a String which has JSONObject inside it like this :
String a = "{"company_name":"ABC","company_address":"hgfh"}";
I added this JSONObject into String with this code :
JSONObject company_one1 = new JSONObject();
company_one1.put("company_name", cmpy_name.getText()
.toString().trim());
company_one1.put("company_address", cmpy_addrs.getText()
.toString().trim());
a = company_one1.toString();
But now I've only the String and I need to add the JSONObject of this String a into an ArrayList and then convert that ArrayList into JSON which should look like :
{"id":"5","data":[{"company_name":"ABC","company_address":"hgfh","image":["cmFodWxtaXNocmE="]}]}
I have tried lots of things to change format like this, but I'm not getting exact format. Sometimes it adds backslashes \ itself into JSON beacuse we can't create a JSON which is already a JSON.
Please give me a proper solution for it.
Thanks in advance.
try this,
JSONArray imageArray = new JSONArray();
imageArray.put("cmFodWxtaXNocmE=");
//* you can add more to the image array by using the put method
JSONObject company_one1 = new JSONObject();
company_one1.put("company_name", cmpy_name.getText()
.toString().trim());
company_one1.put("company_address", cmpy_addrs.getText()
.toString().trim());
//* add the image array
company_one1.put("image", imageArray);
//* create a JSONArray for company types,
JSONArray dataArray = new JSONArray();
dataArray.put(company_one1);
//* you can add more to the array here by using the put method
//* now put all in one main JSONObject
JSONObject mainObj = new JSONObect();
mainObj.put("id", "5");
mainObj.put("data", dataArray);
String finalJsonString = mainObj.toString();
I don't think you are handling with JSON in a right wary. Maybe you should do like this:
try {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("company_name", "company_name");
map1.put("company_address", "company_address");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("company_name", "company_name");
map2.put("company_address", "company_address");
Map<String, String> map3 = new HashMap<String, String>();
map3.put("company_name", "company_name");
map3.put("company_address", "company_address");
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(map1);
list.add(map2);
list.add(map3);
JSONArray jsonArray = new JSONArray(list);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", "5");
jsonObject1.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
Here is the link, if you wish to use GSON as library to serialize and de-serialize json data. Visit Tutorail Java Object to/from JSON and library Gson
Here is pseudo code.(so it could not be compiled maybe)
But Gson is pretty easy and useful.
class Company {
String name;
... // constructors, getter/setters...
}
class CompanyGroup {
int id;
List<Company> companies;
... // constructors, getter/setters...
}
String name = "ABC";
Company a = new Company(name);
int id = 5;
CompanyGroup g = new CompanyGroup(5);
g.companies.add(a);
String r = new Gson().toJson(g);
System.out.println(r);
// I/System.outīš {"companies":[{"name":"ABC"}],"id":5}
I'm using Gson and am trying to add a bunch of string values into a JsonArray like this:
JsonArray jArray = new JsonArray();
jArray.add("value1");
The problem is that the add method only takes a JsonElement.
I've tried to cast a String into a JsonElement but that didn't work.
How do I do it using Gson?
You can create a primitive that will contain the String value and add it to the array:
JsonArray jArray = new JsonArray();
JsonPrimitive element = new JsonPrimitive("value1");
jArray.add(element);
Seems like you should make a new JsonPrimitive("value1") and add that.
See The javadoc
For newer versions of Gson library , now we can add Strings too. It has also extended support for adding Boolean, Character, Number etc. (see more here)
Using this works for me now:
JsonArray msisdnsArray = new JsonArray();
for (String msisdn : msisdns) {
msisdnsArray.add(msisdn);
}
I was hoping for something like this myself:
JsonObject jo = new JsonObject();
jo.addProperty("strings", new String[] { "value1", "value2" });
But unfortunately that isn't supported by GSON so I created this helper:
public static void Add(JsonObject jo, String property, String[] values) {
JsonArray array = new JsonArray();
for (String value : values) {
array.add(new JsonPrimitive(value));
}
jo.add(property, array);
}
And then use it like so:
JsonObject jo = new JsonObject();
Add(jo, "strings", new String[] { "value1", "value2" });
Voila!
In the client side, I have constructed a JSOnARRAY like this:
{"filterEntries":[{"dataName":"mainContact","filterValue":"BILLGATES"}]}.
On the server side (java), I can retireve the values using :
jfilter = JSONValue.parse(jsonFilterStr); //jsonFilterStr={"filterEntries":[{"dataName":"mainContact","filterValue":"BILLGATES"}]}.
JSONArray jFilterEntries = (JSONArray) jfilter.get("filterEntries");
for (int i=0;i<jFilterEntries.size();i++){
JSONObject jFilterEntry = (JSONObject) jFilterEntries.get(i);
String dataName = (String) jFilterEntry.get("dataName");
String filterValue = (String) jFilterEntry.get("filterValue");
}
But the existing app is using flex.json.deserializer and I am unable to achieve the same using flex.json.deserializer. How should I proceed?
I wish to do something like this:
JSONDeserializer jsonDeserializer = new JSONDeserializer();
jsonDeserializer.use(null, List.class);
List<Map<String,String>> lMap= (List<Map<String,String>>)jsonDeserializer.deserialize(params);
Remember the top object that wraps the array. You have to handle that as well. You have to tell it to expect a Map inside the List. To do that you have to specify the type contained in the list by using the path expression "values".
Map<String,List<Map<String,String>>> result = new JSONDeserializer<Map<String,List<Map<String,String>>>>()
.use("values",List.class)
.use("values.values", Map.class)
.deserialize( json);
List<Map<String,String>> filterEntries = result.get("filterEntries");
Updated: Add the new keyword, and made the generic types on the right match the left.