java gson json object array to string array - java

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
}
}
}

Related

Using Gson to convert a string object to JSON string in 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"}

String to JSON array of json objects

I have a Sring s (JSON array) [{"Phonetype":"Pre","Phone":"918282311"},{"Phonetype":"pre","Phone":"918333222"}]
and now i want to convert this string to JSON array of the JSON objects.
in my code i only can create a JSONrray of objects...
#Override
public ArrayList<TelephoneNumber> convertToAttribute(String s) {
ArrayList<TelephoneNumber> list = new ArrayList<TelephoneNumber>();
JSONParser parser = new JSONParser();
JSONArray arr = null;
try {
arr = (JSONArray) parser.parse(s);
}
catch (ParseException e) {
e.printStackTrace();
}
for (JSONObject jo: arr)
{
System.out.println("obj " +jo.get("Phone");
}
//create a list
return list;
}
how create a JsonArray of JsonObjects?
Consider using Gson to parse json values and use FieldNamingPolicy on a GsonBuilder to get a Gson object that handles upper camel case names correctly:
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
Type listType = new TypeToken<ArrayList<TelephoneNumber>>() {}.getType();
List<TelephoneNumber> numbers = gson.fromJson(jsonArray, listType);
I'd recommend taking a look at Gson. It is a series of Java classes written by The Google Overlords that handles serializing and deserializing JSON from and to Java classes.
So, making a few assumptions about what your TelephoneNumber class looks like, you should be able to do this:
Type listType = new TypeToken<ArrayList<TelephoneNumber>>() {
}.getType();
ArrayList<TelephoneNumber> yourList = new Gson().fromJson(s, listType);
Then return yourList....

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