How to provide JSON input directly as a String argument - java

The following code prints the following as input, but I would like to pass this JSON string as input directly to parse method (preferably as string argument). How should I do that?
{"val1":"v1","val2":"v2"}
import com.google.gson.*;
public class ParseJSON {
String val1;
String val2;
transient String val3;
public static void main(String[] args) {
Gson gson = new GsonBuilder().create();
ParseJSON parseJson = new ParseJSON();
parseJson.val1 = "v1";
parseJson.val2 = "v2";
parseJson.val3 = "v3";
String requestBody = gson.toJson(parseJson);
System.out.println(requestBody);
JsonParser parser = new JsonParser();
// JsonArray array = parser.parse(requestBody).getAsJsonArray();
}
}

The JSON that is being created would be considered a JSON object, not an array. To parse it correctly, you would need to call:
JsonObject object = parser.parse(requestBody).getAsJsonObject();
A JSON array would look more like this:
[{"va1": "v1", "val2": "v2", "val3": "v3"}, {"val4": "v4", "val4": "v5", "val5": "v6"}]
That's a JSON array containing two JSON objects. JSON arrays have similar style to arrays you see in Java, they have [ ] brackets and contain a comma separated list of objects/arrays/primitives.
Additionally, you can parse it like this as well:
JsonElement element = parser.parse(requestBody);
Once you have a JsonElement you can call methods like isJsonArray() or isJsonObject() to find out what the top level JSON element is for the String you've parsed.

*You should do that in a following code for your request*
static String val1 = "v1";
static String val2 = "v2";
transient String val3;
public static void main(String[] args) {
JSONArray arrayTable = new JSONArray();
JSONObject node = new JSONObject();
node.put("val1", val1);
node.put("val2", val2);
arrayTable.add(node);
System.out.println(arrayTable);
}
**Dependency lib**:
<dependency>
<groupId>json</groupId>
<artifactId>json</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>

Related

Merge two JSONs to JSONObject instead of JSONArray

I need to find a way how to merge two (or more) JSON objects into a single JSON object without JSON arrays.
There's code example:
public static void mergeJSONs() {
JSONObject jsonObject1 = new JSONObject("{\"1level1\":{\"1level2\":{\"1label1\":\"1value1\"}}}");
JSONObject jsonObject2 = new JSONObject("{\"1level1\":{\"1level2\":{\"1label2\":\"1value2\"}}}");
JSONObject jsonObject3 = new JSONObject("{\"2level1\":{\"2level2\":{\"2level3\":{\"2label1\":\"2value1\"}}}}");
JSONObject jsonObject4 = new JSONObject("{\"2level1\":{\"2level2\":{\"2label2\":\"2value2\"}}}");
JSONObject combined = new JSONObject();
combined.put("strings", jsonObject1);
combined.put("strings", jsonObject2);
combined.put("strings", jsonObject3);
combined.put("strings", jsonObject4);
System.out.println(combined.toString());
}
Output for this code:
{"strings":{"2level1":{"2level2":{"2label2":"2value2"}}}}
Expected output:
{
"strings":{
"1level1":{
"1level2":{
"1label1":"1value1",
"1label2":"1value2"
}
},
"2level1":{
"2level2":{
"2level3":{
"2label1":"2value1"
},
"2label2":"2value2"
}
}
}
}
or in one line:
{"strings":{"1level1":{"1level2":{"1label1":"1value1","1label2":"1value2"}},"2level1":{"2level2":{"2level3":{"2label1":"2value1"},"2label2":"2value2"}}}}
The thing is that I will never know the names of the JSON objects and how deep will this JSON be in the end as this will be used to convert files, so I am not able to create POJO for this.
Currently I'm using org.json library for this but if there is an easy way how to do that with other libraries - it works for me as well.
Library:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
UPDATE #1:
Those objects are provided just for example, in reality JSONs will be larger and deeper. Problem is that I will never know how deep and which keys matches in JSON. So here recursive method is needed which would go through both object until there is any key that matches and one of object doesn't contain that key then all the nested objects should be merged to that one.
UPDATE #2:
Updated sample code and expected output to make image more clear
I prefer and recommend use Gson from Google:
The last release is 2.8.6 from Oct of 2019:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
Always check last version on Maven Central Repository:
https://mvnrepository.com/artifact/com.google.code.gson/gson
Example:
public static void mergeJSONs() {
String JSON1 = "{\"1level1\":{\"1level2\":{\"1label1\":\"1value1\"}}}";
String JSON2 = "{\"1level1\":{\"1level2\":{\"1label2\":\"1value2\"}}}";
String JSON3 = "{\"2level1\":{\"2level2\":{\"2level3\":{\"2label1\":\"2value1\"}}}}";
String JSON4 = "{\"2level1\":{\"2level2\":{\"2label2\":\"2value2\"}}}";
String finalJson = organizeJson(JSON1, JSON2, JSON3, JSON4);
System.out.println(finalJson);
}
The method can receive a list of json payloads, add a root element and merge:
public String organizeJson(String... jsonList) throws Exception {
JsonObject jsonObj = null;
Gson gson = new GsonBuilder().setPrettyPrinting().create();
for (String json : jsonList) {
if (jsonObj != null) {
jsonObj = jsonMerge(jsonObj, gson.fromJson(json, JsonObject.class));
} else {
jsonObj = gson.fromJson(json, JsonObject.class);
}
}
JsonObject jsonStringsRoot = new JsonObject();
/* Add "strings" as root element */
jsonStringsRoot.add("strings", jsonObj);
return gson.toJson(jsonStringsRoot);
}
Method using recursive call to find the last level on nested objects (deep merge):
public static JsonObject jsonMerge(JsonObject jsonA, JsonObject jsonB) throws Exception {
for (Map.Entry<String, JsonElement> sourceEntry : jsonA.entrySet()) {
String key = sourceEntry.getKey();
JsonElement value = sourceEntry.getValue();
if (!jsonB.has(key)) {
if (!value.isJsonNull()) {
jsonB.add(key, value);
}
} else {
if (!value.isJsonNull()) {
if (value.isJsonObject()) {
jsonMerge(value.getAsJsonObject(), jsonB.get(key).getAsJsonObject());
} else {
jsonB.add(key, value);
}
} else {
jsonB.remove(key);
}
}
}
return jsonB;
}
Reference:
https://stackoverflow.com/a/38757661/5626568

Java Gson parse Json object to array

I'm trying to parse the below Json using the Gson lib in Java. When using other languages, such as C#, this JSON is parsed into an array, however it seems Gson converts this into a set of java attributes (which to be honest, makes more sense to me). Does anyone know if I can change this behaviour of the Gson lib?
{
"Outer": {
"0": {
"Attr1": 12345,
"Attr2": 67890
},
"1": {
"Attr1": 54321,
"Attr2": 09876
}
}
}
The below code demonstrates how Gson parses the array as a JsonObject. To be clear, I realise I've referenced outer as a JsonObject but I was just doing this to demonstrate the code. If I try and reference outer as an JsonArray, the code fails.
String json = "{\"Outer\": { \"0\": { \"Attr1\": 12345, \"Attr2\": 67890 }, \"1\": { \"Attr1\": 54321, \"Attr2\": 09876 }}}";
Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setLenient()
.serializeNulls()
.create();
JsonObject jo = gson.fromJson(json, JsonObject.class);
JsonObject outer = jo.getAsJsonObject("Outer");
System.out.println(outer);
System.out.println(outer.isJsonArray());
Result:
{"0":{"Attr1":12345,"Attr2":67890},"1":{"Attr1":54321,"Attr2":"09876"}}
false
//edit
I'm using this current simple Json as an example, however my application of this code will be to parse Json that's of varying and unknown shape. I therefore need Gson to automatically parse this to an array so that the isJsonArray returns true.
TL;DR: See "Using Deserializer" section at the bottom for parsing straight to array.
That JSON does not contain any arrays. An array would use the [...] JSON syntax.
Normally, a JSON object would map to a POJO, with the name in the name/value pairs mapping to a field of the POJO.
However, a JSON object can also be mapped to a Map, which is especially useful when the names are dynamic, since POJO fields are static.
Using Map
The JSON object with numeric values as names can be mapped to a Map<Integer, ?>, e.g. to parse that JSON to POJOs, do it like this:
class Root {
#SerializedName("Outer")
public Map<Integer, Outer> outer;
#Override
public String toString() {
return "Root[outer=" + this.outer + "]";
}
}
class Outer {
#SerializedName("Attr1")
public int attr1;
#SerializedName("Attr2")
public int attr2;
#Override
public String toString() {
return "Outer[attr1=" + this.attr1 + ", attr2=" + this.attr2 + "]";
}
}
Test
Gson gson = new GsonBuilder().create();
Root root;
try (BufferedReader in = Files.newBufferedReader(Paths.get("test.json"))) {
root = gson.fromJson(in, Root.class);
}
System.out.println(root);
Output
Root[outer={0=Outer[attr1=12345, attr2=67890], 1=Outer[attr1=54321, attr2=9876]}]
Get as Array
You can then add a helper method to the Root class to get that as an array:
public Outer[] getOuterAsArray() {
if (this.outer == null)
return null;
if (this.outer.isEmpty())
return new Outer[0];
int maxKey = this.outer.keySet().stream().mapToInt(Integer::intValue).max().getAsInt();
Outer[] arr = new Outer[maxKey + 1];
this.outer.forEach((k, v) -> arr[k] = v);
return arr;
}
Test
System.out.println(Arrays.toString(root.getOuterAsArray()));
Output
[Outer[attr1=12345, attr2=67890], Outer[attr1=54321, attr2=9876]]
Using Deserializer
However, it would likely be more useful if the conversion to array is done while parsing, so you need to write a JsonDeserializer and tell Gson about it using #JsonAdapter:
class Root {
#SerializedName("Outer")
#JsonAdapter(OuterArrayDeserializer.class)
public Outer[] outer;
#Override
public String toString() {
return "Root[outer=" + Arrays.toString(this.outer) + "]";
}
}
class OuterArrayDeserializer implements JsonDeserializer<Outer[]> {
#Override
public Outer[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// Parse JSON array normally
if (json.isJsonArray())
return context.deserialize(json, Outer[].class);
// Parse JSON object using names as array indexes
JsonObject obj = json.getAsJsonObject();
if (obj.size() == 0)
return new Outer[0];
int maxKey = obj.keySet().stream().mapToInt(Integer::parseInt).max().getAsInt();
Outer[] arr = new Outer[maxKey + 1];
for (Entry<String, JsonElement> e : obj.entrySet())
arr[Integer.parseInt(e.getKey())] = context.deserialize(e.getValue(), Outer.class);
return arr;
}
}
Same Outer class and test code as above.
Output
Root[outer=[Outer[attr1=12345, attr2=67890], Outer[attr1=54321, attr2=9876]]]
I'll asume your JsonObject is a POJO class such like:
public Inner[] outer;
If you want an array of objects you can change your code to:
Inner[] jo = gson.fromJson(json, Inner[].class);
Jackson – Marshall String to JsonNode will be useful in your case.with following pom:-
//POM FILE
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
//JAVA CODE
//read json file data to String
byte[] jsonData = Files.readAllBytes(Paths.get("employee.txt"));
//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
//read JSON like DOM Parser
JsonNode rootNode = objectMapper.readTree(jsonData);
JsonNode idNode = rootNode.path("id");
System.out.println("id = "+idNode.asInt());
JsonNode phoneNosNode = rootNode.path("phoneNumbers");
Iterator<JsonNode> elements = phoneNosNode.elements();
while(elements.hasNext()){
JsonNode phone = elements.next();
System.out.println("Phone No = "+phone.asLong());
}
You can use the JsonNode class's method findParent findValue and findPath which reduce your code as compare to another parsing library.
Please refer below code
1.To get an array of Objects (outerArray)
2.You can extract a JsonArray (outerJsonArray) containing values of inner objects in Outer (in case keys aren't significant for further use)
String json = "{\"Outer\": { \"0\": { \"Attr1\": 12345, \"Attr2\": 67890 }, \"1\": { \"Attr1\": 54321, \"Attr2\": 09876 }}}";
Gson gson = new GsonBuilder().disableHtmlEscaping().setLenient().serializeNulls().create();
JsonObject jo = gson.fromJson(json, JsonObject.class);
JsonObject outer = jo.getAsJsonObject("Outer");
Object[] outerArray = outer.entrySet().toArray();
// outerArray: [0={"Attr1":12345,"Attr2":67890}, 1={"Attr1":54321,"Attr2":"09876"}]
JsonArray outerJsonArray = new JsonArray();
outer.keySet().stream().forEach(key -> {
outerJsonArray.add(outer.get(key));
});
//jsonArray=[{"Attr1":12345,"Attr2":67890},{"Attr1":54321,"Attr2":"09876"}]
System.out.println(outer);
System.out.println(outerJsonArray.isJsonArray() + " " + outerJsonArray);

Put String value in gson.JsonArray [duplicate]

This question already has answers here:
How to add a String Array in a JSON object?
(5 answers)
Closed 6 years ago.
I want to store a String in a JsonArray.
Ex:
"virtual_hosts": [ "some_host"]
How should I do this, with the help of java.
JsonArray arr = new JsonArray();
arr.add()
This only lets me add a JsonObject, but I want to store a String.
If you are going to use gson by google, looks like you have to do it this way:
JsonPrimitive firstHost = new JsonPrimitive("vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com");
JsonArray jArray = new JsonArray();
jArray.add(firstHost);
JsonObject jObj = new JsonObject();
jObj.add("virtual_hosts", jArray);
The first line converts your java string into a json string.
In the next two steps, a json array is created and your string is added to it.
After that, a json object which is going to hold the array is created and the array is added with a key that makes the array accessible.
If you inspect the object, it looks exactly like you want to have it.
There is no simple way in adding just a string to an JsonArray if you want to use gson. If you need to add your string directly, you probably have to use another library.
You can create a list of hosts and set the property in JSON.
import org.json.simple.JSONObject;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> hosts = new ArrayList<String>();
hosts.add("vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com");
hosts.add("dummy.oc9qadev.com");
JSONObject jsonObj = new JSONObject();
jsonObj.put("virtual_hosts", hosts);
System.out.println("Final JSON String is--"+jsonObj.toString());
}
}
Output -
{ "virtual_hosts":
["vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com",
"dummy.oc9qadev.com"] }
What you are trying to do is storing a JSONArray into a JSONObject. Because the key virtual_hosts is going to contain a value as JSONArray.
Below code can help you.
public static void main( String[] args ) {
JSONArray jsonArray = new JSONArray();
jsonArray.add( "vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com" );
JSONObject jsonObject = new JSONObject();
jsonObject.put( "virtual_hosts", jsonArray );
System.out.println( jsonObject );
}
Output:
{"virtual_hosts":["vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com"]}
Maven dependecny
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>

How to convert any Object to String?

Here is my code:
for (String toEmail : toEmailList)
{
Log.i("GMail","toEmail: "+toEmail);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
}
Please give me some suggestion about this.
To convert any object to string there are several methods in Java
String convertedToString = String.valueOf(Object); //method 1
String convertedToString = "" + Object; //method 2
String convertedToString = Object.toString(); //method 3
I would prefer the first and third
EDIT
If working in kotlin, the official android language
val number: Int = 12345
String convertAndAppendToString = "number = $number" //method 1
String convertObjectMemberToString = "number = ${Object.number}" //method 2
String convertedToString = Object.toString() //method 3
If the class does not have toString() method, then you can use ToStringBuilder class from org.apache.commons:commons-lang3
pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12</version>
</dependency>
code:
ToStringBuilder.reflectionToString(yourObject)
"toString()" is Very useful method which returns a string representation of an object. The "toString()" method returns a string reperentation an object.It is recommended that all subclasses override this method.
Declaration: java.lang.Object.toString()
Since, you have not mentioned which object you want to convert, so I am just using any object in sample code.
Integer integerObject = 5;
String convertedStringObject = integerObject .toString();
System.out.println(convertedStringObject );
You can find the complete code here.
You can test the code here.
I've written a few methods for convert by Gson library and java 1.8 .
thay are daynamic model for convert.
string to object
object to string
List to string
string to List
HashMap to String
String to JsonObj
//saeedmpt
public static String convertMapToString(Map<String, String> data) {
//convert Map to String
return new GsonBuilder().setPrettyPrinting().create().toJson(data);
}
public static <T> List<T> convertStringToList(String strListObj) {
//convert string json to object List
return new Gson().fromJson(strListObj, new TypeToken<List<Object>>() {
}.getType());
}
public static <T> T convertStringToObj(String strObj, Class<T> classOfT) {
//convert string json to object
return new Gson().fromJson(strObj, (Type) classOfT);
}
public static JsonObject convertStringToJsonObj(String strObj) {
//convert string json to object
return new Gson().fromJson(strObj, JsonObject.class);
}
public static <T> String convertListObjToString(List<T> listObj) {
//convert object list to string json for
return new Gson().toJson(listObj, new TypeToken<List<T>>() {
}.getType());
}
public static String convertObjToString(Object clsObj) {
//convert object to string json
String jsonSender = new Gson().toJson(clsObj, new TypeToken<Object>() {
}.getType());
return jsonSender;
}
I am try to convert Object type variable into string using this line of code
try this to convert object value to string:
Java Code
Object dataobject=value;
//convert object into String
String convert= String.valueOf(dataobject);
I am not getting your question properly but as per your heading, you can convert any type of object to string by using toString() function on a String Object.
try this one
ObjectMapper mapper = new ObjectMapper();
String oldSerial = mapper.writeValueAsString(list);

Convert JsonObject to String

{
"data":
{
"map":
{
"allowNestedValues": true,
"create": "2012-12-11 15:16:13",
"title": "test201212110004",
"transitions": []
}
},
"msg": "success",
"code": "0"
}
Above is a JsonObject, the data is a JsonObject.
How to convert it to a String like "msg":"success" as you know, i can't directly add a double quotes outside data's value.
There is an inbuilt method to convert a JSONObject to a String. Why don't you use that:
JSONObject json = new JSONObject();
json.toString();
You can use:
JSONObject jsonObject = new JSONObject();
jsonObject.toString();
And if you want to get a specific value, you can use:
jsonObject.getString("msg");
or Integer value
jsonObject.getInt("codeNum");
For long Integers
jsonObject.getLong("longNum");
you can use
JsonObject.getString("msg");
You can try Gson convertor, to get the exact conversion like json.stringify
val jsonString:String = jsonObject.toString()
val gson:Gson = GsonBuilder().setPrettyPrinting().create()
val json:JsonElement = gson.fromJson(jsonString,JsonElement.class)
val jsonInString:String= gson.toJson(json)
println(jsonInString)
JsonObject seems to be JSON-P API. If this is true, I would use JsonWritter to write JsonValue into StringWriter:
JsonObjectBuilder pokemonBuilder = Json.createObjectBuilder();
pokemonBuilder.add("name", "Pikachu");
pokemonBuilder.add("type", "electric");
pokemonBuilder.add("cp", 827);
pokemonBuilder.add("evolve", true);
JsonObject pokemon = pokemonBuilder.build();
StringWriter sw = new StringWriter(128);
try (JsonWriter jw = Json.createWriter(sw)) {
jw.write(pokemon);
}
String pokemonStr = sw.toString();
Add a double quotes outside the brackets and replace double quotes inside the {} with \"
So: "{\"data\":{..... }"
Use This :
JSONObject json = new JSONObject();
JSONObject.valueToString(json.toString());
JSONObject metadata = (JSONObject) data.get("map"); //for example
String jsonString = metadata.**toJSONString()**;
just use ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
//here more config opts...
Car car = new Car("yellow", "renault");
objectMapper.writeValue(new File("target/car.json"), car);
String carAsString = objectMapper.writeValueAsString(car);
JSONObject data = (JSONObject) data.get("map");
//for example
String jsonString = data.toJSONString();
Example of Model
public class Person {
private String name;
private String age;
// setter and getter
// toString method
}
Example of Service method
public String getPerson() {
JSONObject returnObj = new JSONObject();
Person person = new Person();
person.setAge("24");
person.setName("Fazal");
returnObj.put("age", person.getAge());
returnObj.put("name", person.getName());
return returnObj.toString();
}
Json in java dependency needed
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>{New_Version}</version>
</dependency>
You will get this type of JSON result
This should get all the values from the above JsonObject
System.out.println(jsonObj.get("msg"));
System.out.println(jsonObj.get("code"));
JsonObject obj= jsonObj.get("data").getAsJsonObject().get("map").getAsJsonObject();
System.out.println(obj.get("allowNestedValues"));
System.out.println(obj.get("create"));
System.out.println(obj.get("title"));
System.out.println(obj.get("transitions"));
You can use reliable library GSON
private static final Type DATA_TYPE_JSON =
new TypeToken<JSONObject>() {}.getType();
JSONObject orderJSON = new JSONObject();
orderJSON.put("noOfLayers", "2");
orderJSON.put("baseMaterial", "mat");
System.out.println("JSON == "+orderJSON.toString());
String dataAsJson = new Gson().toJson(orderJSON, DATA_TYPE_JSON);
System.out.println("Value of dataAsJson == "+dataAsJson.toString());
String data = new Gson().toJson(dataAsJson);
System.out.println("Value of jsonString == "+data.toString());
var data= {"data": {"map":{"allowNestedValues": true,"create": "2012-12-11 15:16:13","title": "test201212110004","transitions": []}},"msg": "success","code": "0"}
o/p:
Object {data: Object, msg: "success", code: "0"}
Use JSON.stringify to convert entire data into string like below
var stringData = JSON.stringify(data);
o/p:
"{"data":{"map":{"allowNestedValues":true,"create":"2012-12-11 15:16:13","title":"test201212110004","transitions":[]}},"msg":"success","code":"0"}"
Use JSON.parse to convert entire string object into JSON Object like below
var orgdata = JSON.parse(stringData);
o/p:
Object {data: Object, msg: "success", code: "0"}
I think you need this :
Suppose you have Sample JSON like this :
{"ParamOne":"InnerParamOne":"InnerParamOneValue","InnerParamTwo":"InnerParamTwoValue","InnerParamThree":"InnerParamThreeValue","InnerParamFour":"InnerParamFourValue","InnerParamFive":"InnerParamFiveValue"}}
Converted to String :
String response = {\"ParamOne\":{\"InnerParamOne\":\"InnerParamOneValue\",\"InnerParamTwo\":\"InnerParamTwoValue\",\"InnerParamThree\":\"InnerParamThreeValue\",\"InnerParamFour\":\"InnerParamFourValue\",\"InnerParamFive\":\"InnerParamFiveValue\"}} ;
Just replace " by \"

Categories

Resources