Using Gson to convert a string object to JSON string in Java - java

Let's say we have the following string:
String x = "abc";
My question is how would I use the Gson library to convert the given string, to the following JSON string:
{
x : "abc"
}

Of course I could have created a new class that wraps the string object, and convert it to a JSON string, but it didn't seem necessary. Anyway, the solution I found was this:
JsonObject x = new JsonObject();
x.addProperty("x", "abc");
String json = x.toString();

http://www.studytrails.com/java/json/java-google-json-parse-json-to-java.jsp
class Albums {
public String x;
}
Lets convert this to JSON and see how it looks
import com.google.gson.Gson;
public class JavaToJsonAndBack {
public static void main(String[] args) {
Albums albums = new Albums();
albums.x= "abc";
Gson gson = new Gson();
System.out.println(gson.toJson(albums));
}
}
This is how the resulting JSON looks like
{"x":"abc"}

Related

java gson json object array to string array

I am a beginner with JAVA and are using the gson library to convert a JSON string something like this:
String json = "{\"Report Title\": \"Simple Embedded Report Example with Parameters\",\"Col Headers BG Color\": \"yellow\",\"Customer Names\":[\"American Souvenirs Inc\",\"Toys4GrownUps.com\",\"giftsbymail.co.uk\",\"BG&E Collectables\",\"Classic Gift Ideas, Inc\"]}";
Gson gson = new Gson();
jsonObject (Map) = gson.fromJson(json, Object.class);
But the problem is I need the "Customer Names" array to be returned as a string array and not an object array.
Can gson do this or would it have to be converted afterwards by somehow detecting the type (array) and then looping over each element converting it to a string array and replacing the object array ?
The added problem is that the JSON field names are not fixed, and there may be multiple arrays contained in the JSON string and all of them need converting.
you can use jsonarray to get specific field
you can find json api JSON
add json text into file or you can use buffer to pass to parameter
String json = "{\"customer_names\" : [...]}";
then
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("Customer Names");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
or you can use GSON something like this
public class JsonPojo {
private String[] customer_names;
public String[] getCustomerNames(){ return this.customer_names;}
}
public class App{
public static main(String[] args) {
Gson gson = new Gson();
JsonPojo thing = gson.fromJson(json, JsonPojo.class);
if (thing.getCustomerNames()!= null)
{
// do what you want
}
}
}

Can we convert a string to JSON Array using the json-simple-1.1.1.jar library?

I want to convert a string into a JSON Array using the json-simple-1.1.1.jar library and came up with the following code,
import org.json.simple.*;
public class RESTclient {
public static void main(String[] args) {
String output = "[{\"Symbol\":\"AMZN\",\"Name\":\"Amazon.com Inc\",\"Exchange\":\"NASDAQ\"},{\"Symbol\":\"VXAZN\",\"Name\":\"CBOE Amazon VIX Index\",\"Exchange\":\"Market Data Express\"}]";
JSONObject jsonObject = new JSONObject(output);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
System.out.println(jsonArray);
}
}
I want the output to be a JSON Array. What am I doing wrong here?
What am I doing wrong here?
You're trying to convert a String that contains a JSON array into a JSONObject
JSONObject jsonObject = new JSONObject(output);
Your content represents a JSON array so parse it as such
JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(output);
Note that other libraries, like Gson and Jackson, have much better abstractions for JSON arrays and objects (JsonArray, ArrayNode). Consider using those instead.

Json Object Array Write in Java line by line

I have a Array with some value
when i store that array i got result like this
[{"id":56678,"Name":"Rehman Agarwal"},{"id":66849,"Name":"Rasul Guha"}]
means in a single line.
but I just want to get output like
[{"id":56678,"Name":"Rehman Agarwal"},
{"id":66849,"Name":"Rasul Guha"}]
new line after JSON object ..
How to do it ?
EDIT : i use JSONObject && JSONArray for create json Object and array respectively
Using gson library you can pretty print your json strings like below -
public static String toPrettyFormat(String jsonString) {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonString).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(json);
return prettyJson;
}
And call it like below -
public void testPrettyPrint() {
String compactJson = "{\"playerID\":1234,\"name\":\"Test\",\"itemList\":[{\"itemID\":1,\"name\":\"Axe\",\"atk\":12,\"def\":0},{\"itemID\":2,\"name\":\"Sword\",\"atk\":5,\"def\":5},{\"itemID\":3,\"name\":\"Shield\",\"atk\":0,\"def\":10}]}";
String prettyJson = toPrettyFormat(compactJson);
System.out.println("Compact:\n" + compactJson);
System.out.println("Pretty:\n" + prettyJson);
}

How to Convert String Array JSON in a Java Object [duplicate]

This question already has answers here:
Convert a JSON string to object in Java ME?
(14 answers)
Closed 8 years ago.
i need to convert this String JSON to a Java Object:
{"estabelecimento":[{"id":"5","idUsuario":"5","razaoSocial":"Bibi LTDA","nomeFantasia":"BibiPizza","telefone":"22121212","email":"ronaldo#bibi.com","gostaram":"0"},{"id":"8","idUsuario":"1","razaoSocial":"Nestor Latuf LTDA","nomeFantasia":"Nestor Sorvetes","telefone":"32343233","email":"nestor#Sorvete.com","foto":"","gostaram":"0"},{"id":"9","idUsuario":"1","razaoSocial":"Comercio Alimenticio Rivaldo","nomeFantasia":"Rogers Burguer","telefone":"210021020","email":"roger#gmail.com","foto":"","gostaram":"0"}]}
I try this, but not work:
//JSONArray jArr = new JSONArray(br.toString());
//JSONObject jObj = new JSONObject(br.toString());
//JSONArray jArr = jObj.getJSONArray("list");
JSONArray jArr = new JSONArray(br.toString());
for (int i=0; i < jArr.length(); i++) {
JSONObject obj = jArr.getJSONObject(i);
estabelecimento.setId(obj.getLong("id"));
estabelecimento.setIdUsuario(obj.getLong("idUsuario"));
estabelecimento.setRazaoSocial(obj.getString("razaoSocial"));
estabelecimento.setNomeFantasia(obj.getString("nomeFantasia"));
estabelecimento.setTelefone(obj.getString("telefone"));
estabelecimento.setEmail(obj.getString("email"));
estabelecimento.setGostaram(obj.getInt("gostaram"));
estabelecimentoList.add(estabelecimento);
}
con.disconnect();
How can i obtain a Java Object? Someone can help? tks.
You can use the Gson lib of google:
public class MyClass {
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 needed
}
String str = {"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]};
com.google.gson.Gson gson = new com.google.gson.Gson();
//To convert json string to class use fromJson
MyClass obj = gson.fromJson(str, MyClass .class);
//To convert class object to json string use toJson
String json = gson.toJson(obj);
At high level two major steps:
Generate a Java class from your JSON, e.g. by using this generator or similar: http://www.jsonschema2pojo.org/
Use Jackson processor to deserialize your JSON file:
ObjectMapper mapper = new ObjectMapper();
YourGeneratedClass obj = (YourGeneratedClass) mapper.readValue(new File("path-to-your-json-file"), YourGeneratedClass.class);
More about Jackson: http://jackson.codehaus.org/
You can also create YourGeneratedClass manually if you feel comfortable enough with this.

How to convert a String to JsonObject using gson library

Please advice how to convert a String to JsonObject using gson library.
What I unsuccesfully do:
String string = "abcde";
Gson gson = new Gson();
JsonObject json = new JsonObject();
json = gson.toJson(string); // Can't convert String to JsonObject
You can convert it to a JavaBean if you want using:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.fromJson(jsonString, JavaBean.class)
To use JsonObject, which is more flexible, use the following:
String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(json);
Assert.assertNotNull(jo);
Assert.assertTrue(jo.get("Success").getAsString());
Which is equivalent to the following:
JsonElement jelem = gson.fromJson(json, JsonElement.class);
JsonObject jobj = jelem.getAsJsonObject();
To do it in a simpler way, consider below:
JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);
I do this, and it worked.
You don't need to use JsonObject. You should be using Gson to convert to/from JSON strings and your own Java objects.
See the Gson User Guide:
(Serialization)
Gson gson = new Gson();
gson.toJson(1); // prints 1
gson.toJson("abcd"); // prints "abcd"
gson.toJson(new Long(10)); // prints 10
int[] values = { 1 };
gson.toJson(values); // prints [1]
(Deserialization)
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String anotherStr = gson.fromJson("[\"abc\"]", String.class)
String emailData = {"to": "abc#abctest.com","subject":"User details","body": "The user has completed his training"
}
// Java model class
public class EmailData {
public String to;
public String subject;
public String body;
}
//Final Data
Gson gson = new Gson();
EmailData emaildata = gson.fromJson(emailData, EmailData.class);
Looks like the above answer did not answer the question completely.
I think you are looking for something like below:
class TransactionResponse {
String Success, Message;
List<Response> Response;
}
TransactionResponse = new Gson().fromJson(response, TransactionResponse.class);
where my response is something like this:
{"Success":false,"Message":"Invalid access token.","Response":null}
As you can see, the variable name should be same as the Json string representation of the key in the key value pair. This will automatically convert your gson string to JsonObject.
Gson gson = new Gson();
YourClass yourClassObject = new YourClass();
String jsonString = gson.toJson(yourClassObject);
Note that as of Gson 2.8.6, instance method JsonParser.parse has been deprecated and replaced by static method JsonParser.parseString:
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");
if you just want to convert string to json then use:
use org.json: https://mvnrepository.com/artifact/org.json/json/20210307
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
import these
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
Now convert it as
//now you can convert string to array and object without having complicated maps and objects
try {
JSONArray jsonArray = new JSONArray("[1,2,3,4,5]");
//you can give entire jsonObject here
JSONObject jsonObject= new JSONObject("{\"name\":\"test\"}") ;
System.out.println("outputarray: "+ jsonArray.toString(2));
System.out.println("outputObject: "+ jsonObject.toString(2));
}catch (JSONException err){
System.out.println("Error: "+ err.toString());
}
You can use the already Gson existing method :
inline fun <I, reified O> I.convert():O {
val json = gson.toJson(this)
return gson.fromJson(json, object : TypeToken<O>() {}.type)
}

Categories