Converting json from a file to a java object - java

I am trying to convert json from a text file into a java object.
I have tried both the jackson library, I put in the dependency and what not. My json file has both camel case and underscores, and that is causing an error when running my program. Here is the code that I used for when relating to the gson librar and it does not do anything, the output is the same with or without the code that I placed.
java.net.URL url = this.getClass().getResource("/test.json");
File jsonFile = new File(url.getFile());
System.out.println("Full path of file: " + jsonFile);
try
{
BufferedReader br = new BufferedReader(new FileReader("/test.json"));
// convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);
System.out.println(obj);
} catch (IOException e)
{
e.printStackTrace();
}
Now I also tried the jackson library. Here is the code i used
java.net.URL url = this.getClass().getResource("/test.json");
File jsonFile = new File(url.getFile());
System.out.println("Full path of file: " + jsonFile);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
InputStream is = Test_Project.class.getResourceAsStream("/test.json");
SampleDto testObj = mapper.readValue(is, SampleDto.class);
System.out.println(testObj.getCreatedByUrl());
I am not sure what to do,

This simple example works like a charm:
DTOs
public class SampleDTO
{
private String name;
private InnerDTO inner;
// getters/setters
}
public class InnerDTO
{
private int number;
private String str;
// getters/setters
}
Gson
BufferedReader br = new BufferedReader(new FileReader("/tmp/test.json"));
SampleDTO sample = new Gson().fromJson(br, SampleDTO.class);
Jackson
InputStream inJson = SampleDTO.class.getResourceAsStream("/test.json");
SampleDTO sample = new ObjectMapper().readValue(inJson, SampleDTO.class);
JSON (test.json)
{
"name" : "Mike",
"inner": {
"number" : 5,
"str" : "Simple!"
}
}

public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
/**
* Read object from file
*/
Person person = mapper.readValue(new File("/home/document/person.json"), Person.class);
System.out.println(person);
}

A common way of getting both array of json in file or simply json would be
InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, Employee.class);
List<Employee> lstEmployees = mapper.readValue(inputStream, collectionType);
The file.json needs to be placed in the resources folder. If your file only has a json block without json array square brackets [] , you can skip the CollectionType
InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
Employee employee = mapper.readValue(inputStream, Employee.class);
Also refer here for original question from where I have drawn.

Related

How to parse multiple JSON objects from a file in Java using URL

I have multiple JSON objectsavailable inside a text file and I am trying to get data from each of them to get some data and store it in my database. The following is a sample of the data I have :
{"address":"4565 S Wayside Dr","categories":["Other Textile Goods","Textile Manufacturers"],"city":"Houston","country":"US","dateAdded":"2016-11-17T22:36:43Z","dateUpdated":"2017-09-12T14:29:52Z","keys":["us/tx/houston/4565swaysidedr/-1836686262"],"latitude":"29.6981","longitude":"-95.3212","name":"Radium Textiles LLC","phones":["7136901081"],"postalCode":"77087","province":"TX","sourceURLs":["http://www.citysearch.com/profile/607780624/houston_tx/radium_textiles_llc.html"],"id":"AVwdH8-KkufWRAb52ixf"}
{"address":"6104 Donoho St","categories":["Wholesale Textile Brokers","Textile Brokers"],"city":"Houston","country":"US","dateAdded":"2017-03-26T19:08:42Z","dateUpdated":"2017-03-26T19:08:42Z","imageURLs":["http://images1.citysearch.net/assets/guide/images/logo_citysearch_130x25.gif"],"keys":["us/tx/houston/6104donohost/-214331342"],"latitude":"29.677891","longitude":"-95.324173","name":"T A Textiles","phones":["7136452800"],"postalCode":"77033","province":"TX","sourceURLs":["http://www.superpages.com/bp/houston-tx/t-a-textiles-L2170967950.htm","http://houston.citysearch.com/profile/647921770/houston_tx/t_a_textiles.html"],"id":"AVwdbMI6IN2L1WUfvriy"}
{"address":"4544 S Pinemont Dr","categories":["Other Fabricated Textile Product Manufacturers","Textile Manufacturers","Other Textile Goods"],"city":"Houston","country":"US","dateAdded":"2016-11-17T22:33:12Z","dateUpdated":"2017-09-12T14:29:50Z","keys":["us/tx/houston/4544spinemontdr/-1836686262"],"latitude":"29.8369","longitude":"-95.5160","name":"Radium Textiles LLC","neighborhoods":["Fairbanks/ Northwest Crossing , Northwest Houston"],"phones":["7136901390"],"postalCode":"77041","province":"TX","sourceURLs":["http://www.citysearch.com/profile/694636660/houston_tx/radium_textiles_llc.html","http://www.yellowpages.com/houston-tx/mip/radium-textiles-456243882?lid=456243882"],"websites":["http://api.citygridmedia.com/content/places/v2/click?q=9YKflVKbY9NauPJdMy0B1gS1IhB4xv4EWw0zDoT-UWc_izWF3zs5PKGdfOHubWrvM0QwDCYwbOH2fdLi0dK5xArULcksCCbfR-WWAz9xD1AmGVAQZIom4U3n5R4DuRC8WJCtvJcNItEKoCSfzwapuGnmwGnHDpEGYXGjnN4u8zXqkiimSHFf4_dbqGRbVgNJczcRYGsO7BQjsEDjdlUTJ3CxVQB3K1438yd7WPe-AAAIJEq588kBWNDLbak0Vs-EUxvQmWKBKxWI5ahci9eDn5KNvXpHpqZUL_e0UVacwelpEs92aC0Q2f_N0ZyiviGOHw8dOG3WIXM3rnMIStdm3v06ddF7lICNJl77Z6Y_mtMiylGr2EYGE_lU-dhl6pZnJ92MqQhlZpOjEubWZv1Bd95b8A-INOGKto848V3VdJNGPJwFN_DkdeWGF8YMvDWgew1xs3RSeBeHcBqFzLqQkDbgIllvuxl9VON3HBMwPYjMZ0kqzhi02JRzW0rO_gItNZKuHfHb3rNrWctuJQ2Qvup-kEiLHf5Hya_5KCAgn6uOStAioAXszLKlglJqFMNQE39j6ieFhMg&placement=listing_profile&cs_user=unknown&cs_session=88473fea2af4b100b0e7993b2eafa4bedbe4234c"],"id":"AVwczWsPkufWRAb5zLcG"}
{"address":"7085 Alameda Ave","categories":["Other Textile Goods","Textile Manufacturers","Textile Finishers","Wholesale Textiles"],"city":"El Paso","country":"US","dateAdded":"2017-06-27T05:29:45Z","dateUpdated":"2017-09-06T17:24:47Z","keys":["us/tx/elpaso/7085alamedaave/-266489986"],"latitude":"31.7550","longitude":"-106.3926","name":"Midwest Textile Co","phones":["9158811790"],"postalCode":"79915","province":"TX","sourceURLs":["http://www.citysearch.com/profile/620236204/el_paso_tx/midwest_textile_co.html"],"id":"AVzoBujQLD2H7whiXdiR"}
I am trying to parse it as follows:
InputStream resourceInputStream = context.getResourceAsStream("/WEB-INF/jsp/modules/data/20180427-businesses.txt");
String jsonString = IOUtils.toString(resourceInputStream, "UTF-8");
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonString );
String address = json.getString("address");
But since the data is not a single JSON string, this is not working correctly. Also, the data I have is not inside an array and that has made things more difficult for me. I also tried to create a Java Class with similar variables and tried to map the JSON string directly to that class, and it was also not working for me.
InputStream resourceInputStream = context.getResourceAsStream("/WEB-INF/jsp/modules/data/20180427-businesses.txt");
String jsonString = IOUtils.toString(resourceInputStream, "UTF-8");
ObjectMapper mapper = new ObjectMapper();
BusinessDataImportHB records = mapper.readValue(jsonString, BusinessDataImportHB.class);
Where:
public class BusinessDataImportHB
{
private List<BusinessRecord> records;
public List<BusinessRecord> getRecords() {
return records;
}
public void setRecords(List<BusinessRecord> records) {
this.records = records;
}
}
and
public class BusinessRecord {
private String address;
private List<String> categories;
private String city;
private String country;
private Date dateAdded;
private Date dateUpdated;
private List<String> keys;
private String latitude;
private String longitude;
private String name;
private List<String> phones;
private String postalCode;
private String province;
private List<String> websites;
private String id;
I cannot change the format of the data. What is the best approach I could use to parse the data and get individual records?
If each JSON Object is in one line you could read the file line by line.
try (Stream<String> stream = Files.lines(Paths.get("..."))) {
stream.forEach(line -> {
JSONObject json = (JSONObject) JSONSerializer.toJSON(line);
String address = json.getString("address");
});
}
If your records are on a line-by-line basis and you have a large file, you may want to consider reading and parsing line by line. You can use a try-with-resources block to ensure no memory leaks from unclosed resources.
String pathname = "/home/william/test.txt"; // your file
try (Scanner sc = new Scanner(new FileInputStream(new File(pathname)))) {
while (sc.hasNextLine()) {
JSONObject json = (JSONObject) JSONSerializer.toJSON(sc.nextLine());
// TODO do something with it
}
} catch (Exception e) {
// TODO
}

Java Properties file to JSON using Jackson

I would like to convert a Java Properties file into JSON with nested objects. I followed an example I found here but I can't get it to work.
For example, given:
objectA.version=1.0
objectA.hostname=192.168.0.11
objectA.port=9989
objectB.hostname=10.0.2.15
objectB.port=9998
I want:
{
“objectA” : {
"version” : "1.0"
"host” : “192.168.0.11”,
"port" : 9989
},
“objectB” : {
"host” : “10.0.2.15”,
"port" : 9998
}
}
This is what I have so far:
static class Endpoint
{
#JsonProperty("objectA")
public ObjectA objectA;
#JsonProperty("objectB")
public ObjectB objectB;
}
static class ObjectA
{
public String hostname;
public String port;
public String version;
}
static class ObjectB
{
public String hostname;
public String port;
}
try (InputStream input = getClass().getClassLoader().getResourceAsStream("file.properties"))
{
JavaPropsMapper mapper = new JavaPropsMapper();
Endpoint host = mapper.readValue(input, Endpoint.class);
String asText = mapper.writeValueAsString(host);
System.out.println(asText);
}
The output looks like this:
objectA.version=1.0
objectA.hostname=192.168.0.11
objectA.port=9989
objectB.hostname=10.0.2.15
objectB.port=9998
I figured it out.
try (InputStream input = getClass().getClassLoader().getResourceAsStream("file.properties"))
{
JavaPropsMapper mapper = new JavaPropsMapper();
Endpoint host = mapper.readValue(input, Endpoint.class);
// String asText = mapper.writeValueAsString(host);
// add this
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String asText = ow.writeValueAsString(host);
//
System.out.println(asText);
}
Not sure if the OP needs an interim object OR if he just wants to get from a props file to a JSON representation of it. If it is the latter then it's easier to just use the databind ObjectNode class as the interim. E.g.
try (InputStream input = new FileInputStream("path_to.properties")) {
JavaPropsMapper mapper = new JavaPropsMapper();
ObjectNode node = mapper.readValue(input, ObjectNode.class);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
// Alternatively write to file ???
System.out.println(ow.writeValueAsString(node);
} catch (IOException e) {
// Do something
}

Json jackson : can't parse a json a file

I m trying to parse a JSON file and store it in an list. I m getting this error :
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
Here is my JSON file
{ "budgetList":[
{
"label":"Salary Tim",
"category":"Monthly Income",
"real":1590,
"estimated":1590,
"date":"",
"month":"",
"year":"",
"type":"Income"
},
{
"label":"Salary Tom",
"category":"Monthly Income",
"real":1540,
"estimated":1540,
"date":"",
"month":"",
"year":"",
"type":"Income"
}
]
}
Here is my code
Budget :
public class Budget {
private String label;
private String category;
private int real;
private int estimated;
private Date date;
private int year;
private String type;
....
....
}
My service :
List<Budget> budgets = objectMapper.readValue(new File("src/main/resources/json/new_exercise.json"), TypeFactory.defaultInstance().constructCollectionType(List.class,
Budget.class));
Where am I wrong?
Thanks in advance.
ANSWER FOUND
Code is
ObjectMapper objectMapper = new ObjectMapper();
List<Budget> budgets = null;
JsonNode node = objectMapper.readTree(new File("src/main/resources/json/new_exercise.json"));
node = node.get("budgetList");
TypeReference<List<Budget>> typeRef = new TypeReference<List<Budget>>(){};
budgets = objectMapper.readValue(node.traverse(), typeRef);
can you, use GSON library? Is very simple
Reader reader = new InputStreamReader(new
FileInputStream("/opt/file.json"));
Gson gson = gsonBuilder.create();
List listBudget = gson.fromJson(reader, new
TypeToken>() {}.getType());
I think that the only problem is when Date and integer parser when is empty. but you can register adapters like:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
throws JsonParseException {
try {
return df.parse(json.getAsString());
} catch (ParseException e) {
return null;
}
}
});
Reader reader = new InputStreamReader(new
FileInputStream("/opt/file.json"));
Gson gson = gsonBuilder.create();
List listBudget = gson.fromJson(reader, new
TypeToken>() {}.getType());
It works for you?, and dont forget to validate you json. "

How to convert list data into json in java

I have a function which is returning Data as List in java class. Now as per my need, I have to convert it into Json Format.
Below is my function code snippet:
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
return cartList;
}
I tried To convert into json by using this code but it is giving type mismatch error as function is of type List...
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
return jsonCartList;
}
Please help me resolve this.
Using gson it is much simpler. Use following code snippet:
// create a new Gson instance
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
Converting back from JSON string to your Java object
// Converts JSON string into a List of Product object
Type type = new TypeToken<List<Product>>(){}.getType();
List<Product> prodList = gson.fromJson(jsonCartList, type);
// print your List<Product>
System.out.println("prodList: " + prodList);
public static List<Product> getCartList() {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", "1");
formDetailsJson.put("name", "name1");
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format
return cartList;
}
you can get the data in the following form
{
"forms": [
{ "id": "1", "name": "name1" },
{ "id": "2", "name": "name2" }
]
}
Try these simple steps:
ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();
i wrote my own function to return list of object for populate combo box :
public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
try {
Object[] args={};
Class cl = Class.forName(kelas);
Method getName = cl.getMethod(name, null);
Method getLabel = cl.getMethod(label, null);
String json="[";
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
if(i>0){
json+=",";
}
json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
//System.out.println("Object = " + i+" -> "+o.getNumber());
}
json+="]";
return json;
} catch (ClassNotFoundException ex) {
Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
System.out.println("Error in get JSON List");
ex.printStackTrace();
}
return "";
}
and call it from anywhere like :
String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");
Try like below with Gson Library.
Earlier Conversion List format were:
[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]
and here the conversion source begins.
//** Note I have created the method toString() in Product class.
//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();
//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();
//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());
//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();
//Run while loop till Product Object exists.
while(iterator.hasNext()){
//Creating a fresh Gson Object
Gson gs = new Gson();
//Converting our Product Object to JsonElement
//Object by passing the Product Object String value (iterator.next())
JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);
//Creating JsonObject from JsonElement
JsonObject jsonObject = element.getAsJsonObject();
//Collecting the JsonObject to List
entities.add(jsonObject);
}
//Do what you want to do with Array of JsonObject
System.out.println(entities);
Converted Json Result is :
[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]
Hope this would help many guys!
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<String> ls =new ArrayList<String>();
for(product cj:cities.getList()) {
ls.add(cj);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", cj.id);
formDetailsJson.put("name", cj.name);
jsonArray.put(formDetailsJson);
}
responseDetailsJson.put("Cities", jsonArray);
return responseDetailsJson;
You can use the following method which uses Jackson library
public static <T> List<T> convertToList(String jsonString, Class<T> target) {
if(StringUtils.isEmpty(jsonString)) return List.of();
return new ObjectMapper().readValue(jsonString, new ObjectMapper().getTypeFactory().
constructCollectionType(List.class, target));
} catch ( JsonProcessingException | JSONException e) {
e.printStackTrace();
return List.of();
}
}
if response is of type List , res.toString() is simply enough to convert to json or else we need to use
ObjectMapper mapper = new ObjectMapper();
String jsonRes = mapper.writeValueAsString(res);

How to parse a JSON Input stream

I am using java to call a url that returns a JSON object:
url = new URL("my URl");
urlInputStream = url.openConnection().getInputStream();
How can I convert the response into string form and parse it?
I would suggest you have to use a Reader to convert your InputStream in.
BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
new JSONObject(responseStrBuilder.toString());
I tried in.toString() but it returns:
getClass().getName() + '#' + Integer.toHexString(hashCode())
(like documentation says it derives to toString from Object)
All the current answers assume that it is okay to pull the entire JSON into memory where the advantage of an InputStream is that you can read the input little by little. If you would like to avoid reading the entire Json file at once then I would suggest using the Jackson library (which is my personal favorite but I'm sure others like Gson have similar functions).
With Jackson you can use a JsonParser to read one section at a time. Below is an example of code I wrote that wraps the reading of an Array of JsonObjects in an Iterator. If you just want to see an example of Jackson, look at the initJsonParser, initFirstElement, and initNextObject methods.
public class JsonObjectIterator implements Iterator<Map<String, Object>>, Closeable {
private static final Logger LOG = LoggerFactory.getLogger(JsonObjectIterator.class);
private final InputStream inputStream;
private JsonParser jsonParser;
private boolean isInitialized;
private Map<String, Object> nextObject;
public JsonObjectIterator(final InputStream inputStream) {
this.inputStream = inputStream;
this.isInitialized = false;
this.nextObject = null;
}
private void init() {
this.initJsonParser();
this.initFirstElement();
this.isInitialized = true;
}
private void initJsonParser() {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonFactory jsonFactory = objectMapper.getFactory();
try {
this.jsonParser = jsonFactory.createParser(inputStream);
} catch (final IOException e) {
LOG.error("There was a problem setting up the JsonParser: " + e.getMessage(), e);
throw new RuntimeException("There was a problem setting up the JsonParser: " + e.getMessage(), e);
}
}
private void initFirstElement() {
try {
// Check that the first element is the start of an array
final JsonToken arrayStartToken = this.jsonParser.nextToken();
if (arrayStartToken != JsonToken.START_ARRAY) {
throw new IllegalStateException("The first element of the Json structure was expected to be a start array token, but it was: " + arrayStartToken);
}
// Initialize the first object
this.initNextObject();
} catch (final Exception e) {
LOG.error("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
throw new RuntimeException("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
}
}
private void initNextObject() {
try {
final JsonToken nextToken = this.jsonParser.nextToken();
// Check for the end of the array which will mean we're done
if (nextToken == JsonToken.END_ARRAY) {
this.nextObject = null;
return;
}
// Make sure the next token is the start of an object
if (nextToken != JsonToken.START_OBJECT) {
throw new IllegalStateException("The next token of Json structure was expected to be a start object token, but it was: " + nextToken);
}
// Get the next product and make sure it's not null
this.nextObject = this.jsonParser.readValueAs(new TypeReference<Map<String, Object>>() { });
if (this.nextObject == null) {
throw new IllegalStateException("The next parsed object of the Json structure was null");
}
} catch (final Exception e) {
LOG.error("There was a problem initializing the next Object: " + e.getMessage(), e);
throw new RuntimeException("There was a problem initializing the next Object: " + e.getMessage(), e);
}
}
#Override
public boolean hasNext() {
if (!this.isInitialized) {
this.init();
}
return this.nextObject != null;
}
#Override
public Map<String, Object> next() {
// This method will return the current object and initialize the next object so hasNext will always have knowledge of the current state
// Makes sure we're initialized first
if (!this.isInitialized) {
this.init();
}
// Store the current next object for return
final Map<String, Object> currentNextObject = this.nextObject;
// Initialize the next object
this.initNextObject();
return currentNextObject;
}
#Override
public void close() throws IOException {
IOUtils.closeQuietly(this.jsonParser);
IOUtils.closeQuietly(this.inputStream);
}
}
If you don't care about memory usage, then it would certainly be easier to read the entire file and parse it as one big Json as mentioned in other answers.
For those that pointed out the fact that you can't use the toString method of InputStream like this see https://stackoverflow.com/a/5445161/1304830 :
My correct answer would be then :
import org.json.JSONObject;
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
...
JSONObject json = new JSONObject(convertStreamToString(url.openStream());
If you like to use Jackson Databind (which Spring uses by default for its HttpMessageConverters), then you may use the ObjectMapper.readTree(InputStream) API. For example,
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(myInputStream);
use jackson to convert json input stream to the map or object http://jackson.codehaus.org/
there are also some other usefull libraries for json, you can google: json java
Use a library.
GSON
Jackson
or one of many other JSON libraries that are out there.
Kotlin version with Gson
to read the response JSON:
val response = BufferedReader(
InputStreamReader(conn.inputStream, "UTF-8")
).use { it.readText() }
to parse response we can use Gson:
val model = Gson().fromJson(response, YourModelClass::class.java)
This example reads all objects from a stream of objects,
it is assumed that you need CustomObjects instead of a Map:
ObjectMapper mapper = new ObjectMapper();
JsonParser parser = mapper.getFactory().createParser( source );
if(parser.nextToken() != JsonToken.START_ARRAY) {
throw new IllegalStateException("Expected an array");
}
while(parser.nextToken() == JsonToken.START_OBJECT) {
// read everything from this START_OBJECT to the matching END_OBJECT
// and return it as a tree model ObjectNode
ObjectNode node = mapper.readTree(parser);
CustomObject custom = mapper.convertValue( node, CustomObject.class );
// do whatever you need to do with this object
System.out.println( "" + custom );
}
parser.close();
This answer was composed by using : Use Jackson To Stream Parse an Array of Json Objects and Convert JsonNode into Object
I suggest use javax.json.Json factory as less verbose possible solution:
JsonObject json = Json.createReader(yourInputStream).readObject();
Enjoy!
if you have JSON file you can set it on assets folder then call it using this code
InputStream in = mResources.getAssets().open("fragrances.json");
// where mResources object from Resources class
{
InputStream is = HTTPClient.get(url);
InputStreamReader reader = new InputStreamReader(is);
JSONTokener tokenizer = new JSONTokener(reader);
JSONObject jsonObject = new JSONObject(tokenizer);
}

Categories