I have a json file.
{
"data" : [
"my/path/old",
"my/path/new"
]
}
I need to conver it to ArrayList of String. How to do it using Jackson library?
UPD:
My code:
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(FileReader.class.getResourceAsStream(file)));
List<String> list = (ArrayList) gson.fromJson(reader, ArrayList.class);
for (String s : list) {
System.out.println(s);
}
And my exception:
Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1
My new update
UPD2:
Gson gson = new Gson();
Type list = new TypeToken<List<String>>(){}.getType();
JsonReader reader = new JsonReader(new InputStreamReader(FileReader.class.getResourceAsStream(file)));
List<String> s = gson.fromJson(reader, list);
System.out.println(s);
You've tagged Jackson but are using Gson in your example. I'm going to go with Jackson
String json = "{\"data\":[\"my/path/old\",\"my/path/new\"]}"; // or wherever you're getting it from
Create your ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Read the JSON String as a tree. Since we know it's an object, you can cast the JsonNode to an ObjectNode.
ObjectNode node = (ObjectNode)mapper.readTree(json);
Get the JsonNode named data
JsonNode arrayNode = node.get("data");
Parse it into an ArrayList<String>
ArrayList<String> data = mapper.readValue(arrayNode.traverse(), new TypeReference<ArrayList<String>>(){});
Printing it
System.out.println(data);
gives
[my/path/old, my/path/new]
Related
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
}
}
}
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....
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);
}
Edited. Anyone know how to read the record in every new line. The below code can only read 1 sentence.
JSONParser parser = new JSONParser();
try
{
Object obj = parser.parse(new FileReader("src/test.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
}
Many ways. I suggest you use google-gson
You can use codehouse jackson
ObjectMapper mapper = new ObjectMapper();
BufferedReader br = new BufferedReader(new FileReader(tweets));
Map<String, Object> json_as_map = mapper.readValue(br, new TypeReference<Map<String, Object>>() {});
After that you can traverse your map or arraylist according to ur structure.
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)
}