How to parse a JSON Input stream - java

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

Related

Reading JSON from file using GSON in Android Studio

I'm trying to read JSON from an internal storage file into a list of objects.
My code for reading the file and GSON is:
fis = openFileInput(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
StringBuilder data = new StringBuilder();
String line = null;
line = reader.readLine();
while (line != null)
{
data.append(line).append("\n");
}
data.toString();
reader.close();
fis.close();
Type walletListType = new TypeToken<ArrayList<WalletClass>>(){}.getType();
walletList.add(new Gson().fromJson(data, walletListType));
However, I'm getting the error
Cannot resolve method fromJson('java.lang.stringBuilder,
java.lang.reflect.Type')
The JSON I'm trying to load is (it's inside the square brackets because I've serialized it from a list of objects):
[
{"balance":258,"walletName":"wallet 1"},
{"balance":5222,"walletName":"wallet 2"},
{"balance":1,"walletName":"wallet 3"}
]
I know a common fix for this is changing the import code from org to com, however I've already made sure it is com.
the Gson provide a lot of overloads for the fromJson method, here are their signatures:
But as you can see none of them takes the StringBuilder as first argument. That is what the compiler is complaining about. Instead you have constructors that take a String as first argument.
So replace this line:
walletList.add(new Gson().fromJson(data, walletListType));
with:
walletList.add(new Gson().fromJson(data.toString(), walletListType));
And you should be good to go.
You can use GSON's Type adapter to read and write files.
I have written this in kotlin, I hope it helps you.
val builder = GsonBuilder()
builder.registerTypeAdapter(YourData::class.java, MyTypeAdapter())
return builder.create()
Sample Type Adapter
class MyTypeAdapter : TypeAdapter<YourData>() {
#Throws(IOException::class)
override fun read(reader: JsonReader): YourData {
var element1
var element2
reader.beginObject()
while (reader.hasNext()) {
when (reader.nextName()) {
"element1" -> latitude = reader.nextDouble()
"element2" -> dropMessage = reader.nextString()
}
}
reader.endObject()
return YourData(element1, element2)
}
#Throws(IOException::class)
override fun write(out: JsonWriter, yourData: YourData) {
out.beginObject()
out.name("element1").value(yourData)
out.name("element2").value(yourData)
out.endObject()
}
}
Usage (Read & Write)
fun saveData(yourData: YourData) {
val string = gson.toJson(yourData)
try {
val dataStream = dataOutputStream(yourData)
yourStream.write(string.toByteArray())
yourStream.close()
} catch (e: IOException) {
Log.e("FileRepository", "Error")
}
}
fun getData(): List<YourData> {
val data = mutableListOf<YourData>()
try {
val fileList = dataDirectory().list()
fileList.map { convertStreamToString(YourDataInputStream(it)) }.mapTo(data) {
gson.fromJson(it, YourData::class.java)
}
} catch (e: IOException) {
Log.e("FileRepository", "Error")
}
return data
}

Cut too long strings in json using gson

I would like to cut too long strings in json.
In order to do that I would like to register new type adapter for String type and inside this deserializer I will check and limit too long strings.
Gson gson = new GsonBuilder().registerTypeAdapter(String.class, new CuttingStringDeserializer()).create();
JsonElement element = gson.fromJson(jsonString, JsonElement.class);
return new GsonBuilder().setPrettyPrinting().create().toJson(element);
Example of json file that I want to process:
{
"myString": "this string is too long - cut it",
"other": "this is ok"
}
Desired output:
{
"myString": "this strin",
"other": "this is ok"
}
In general I don't know structure of json but I want to filter all string occurrences.
Deserializer:
public class CuttingStringDeserializer implements JsonDeserializer<String> {
#Override
public String deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
throws JsonParseException {
String s = json.getAsString();
if(s.lenght() > MAX_CONTENT_LENGTH){
return s.substring(0, MAX_CONTENT_LENGTH);
}else{
return s;
}
}
Unfortunately my custom deserializer is not called by gson.
This (using some custom JsonWriter) works:
package so41793888;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.stream.JsonWriter;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.io.StringWriter;
public class Demo {
public static void main(String[] args) {
String jsonString = "{\n" +
" \"myString\": \"this string is too long - cut it\",\n" +
" \"other\": \"this is ok\"\n" +
"}";
Gson gson = new GsonBuilder().create();
JsonElement element = gson.fromJson(jsonString, JsonElement.class);
StringWriter out = null;
try {
out = new StringWriter();
new GsonBuilder().create().toJson(element, new MyJsonWriter(out));
System.out.println(out.getBuffer().toString());
} finally {
IOUtils.closeQuietly(out);
}
}
private static class MyJsonWriter extends JsonWriter {
public MyJsonWriter(final StringWriter out) {
super(out);
setIndent(" ");
}
#Override
public JsonWriter value(final String value) throws IOException {
return super.value(StringUtils.abbreviate(value, 12));
}
}
}
outputs:
{
"myString": "this stri...",
"other": "this is ok"
}
You can reject the idea of tree processing (the way how JsonSerializer and JsonDeserializer work) in favor of stream processing, where you analyze every token on your own. GsonBuilder seems not to allow overriding a streaming-fashioned TypeAdapters as well, but you can then use JsonReader in order to parse every token from an input stream, and JsonWriter to emit processed tokens to an output stream. This may look too low level, but since it's a streaming way, it is really cheap and does not consume much memory as tree processing usually does. Thus you can process even infinite streams.
#SuppressWarnings("resource")
private static void trim(final int maxStringLength, final Reader reader, final Writer writer)
throws IOException {
// a specifically configured IDEA complains for the unclosed jsonReader, but invoking the `close` method is a like a chain and sometimes undesirable
#SuppressWarnings("all")
final JsonReader jsonReader = new JsonReader(reader);
// the same goes to jsonWriter
#SuppressWarnings("all")
final JsonWriter jsonWriter = new JsonWriter(writer);
for ( JsonToken token; (token = jsonReader.peek()) != END_DOCUMENT; ) {
switch ( token ) {
case BEGIN_ARRAY:
// merely reflect a BEGIN_ARRAY token
jsonReader.beginArray();
jsonWriter.beginArray();
break;
case END_ARRAY:
// merely reflect an END_ARRAY token
jsonReader.endArray();
jsonWriter.endArray();
break;
case BEGIN_OBJECT:
// merely reflect a BEGIN_OBJECT token
jsonReader.beginObject();
jsonWriter.beginObject();
break;
case END_OBJECT:
// merely reflect an END_OBJECT token
jsonReader.endObject();
jsonWriter.endObject();
break;
case NAME:
// merely reflect NAME tokens (or trim?)
jsonWriter.name(jsonReader.nextName());
break;
case STRING:
// trimming a STRING token if necessary
final String string = jsonReader.nextString();
jsonWriter.value(string.length() > maxStringLength ? string.substring(0, maxStringLength) : string);
break;
case NUMBER:
// NUMBER tokens are a bit complex because JSON only denotes a double number that can be literally an integer
final String rawNumber = jsonReader.nextString();
try {
// try to write the biggest integer number supported by Java, floating points also fail to be parsed as long values
jsonWriter.value(parseLong(rawNumber));
} catch ( final NumberFormatException nex1 ) {
try {
// not a long value, then perhaps it's a double value?
jsonWriter.value(parseDouble(rawNumber));
} catch ( final NumberFormatException nex2 ) {
// can't think of specific cases here...
throw new AssertionError("Must not happen", nex2);
}
}
break;
case BOOLEAN:
// merely reflect BOOLEAN tokens
jsonWriter.value(jsonReader.nextBoolean());
break;
case NULL:
// merely reflect NULL tokens
jsonReader.nextNull();
jsonWriter.nullValue();
break;
case END_DOCUMENT:
// fall through, because this type of tokens is checked above, and it's fine to throw an assertion error
default:
throw new AssertionError(token);
}
}
}
This method, of course, does not support pretty printing, but it can be easily implemented if it's really necessary.
And how it's used:
final Reader reader = new StringReader("{\"myString\":\"this string is too long - cut it\",\"other\":\"this is ok\"}");
final Writer writer = new OutputStreamWriter(System.out); // redirect the output to System.out
trim(10, reader, writer);
writer.flush(); // flushing at a call-site, we decide
The output:
{"myString":"this strin","other":"this is ok"}
The solution can work with any kind of JSON, having no background for a particular type. Simply speaking, it's just type-unaware and can process even simple single literals like "foo-bar-baz-qux".
It seems for me it doesn't make sense what are you trying to archive, but here kick off code which should help .
public class Main {
private static String json = "{\"myString\": \"this string is too long - limit it\",\"other\": \"this is ok\"}";
public static void main(String... var) {
System.out.print(cutJson(json));
}
public static String cutJson(String json) {
Type type = new TypeToken<Map<String, String>>() {
}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(type, new CuttingStringDeserializer()).create();
Map<String, String> element = gson.fromJson(json, type);
return new GsonBuilder().setPrettyPrinting().create().toJson(element);
}
private static class CuttingStringDeserializer implements JsonDeserializer<Map<String, String>> {
#Override
public Map<String, String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Iterator<Map.Entry<String, JsonElement>> iterator = ((JsonObject) json).entrySet().iterator();
Map<String, String> result = new HashMap<String, String>();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
if (entry.getValue().getAsString().length() > 10) {
entry.setValue(new JsonPrimitive(entry.getValue().getAsString().substring(0, 9)));
}
result.put(entry.getKey(), entry.getValue().getAsString());
}
return result;
}
}
}
Prints:
{
"myString": "this stri",
"other": "this is ok"
}

AsyncTask doInBackground to return multiple strings

I'm trying to build a very basic weather app in android studio. I am using AsyncClass to return multiple strings.
As you can see in the code, I used a class named "Wrapper" that is used to store my strings so I can just return a class object and use it in the onPostExecute method of the AsyncTask. The problem I am facing is that when I test the app, all of the returned Strings somehow are undefined (the default for the Wrapper class). This means the strings are not being updated in the doInBackground method and I can't seem to figure out why!
My Activity
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(MainActivity.class.getSimpleName(), "Can't connect to Google Play Services!");
}
private class Wrapper
{
String Temperature = "UNDEFINED";
String city = "UNDEFINED";
String country = "UNDEFINED";
}
private class GetWeatherTask extends AsyncTask<String, Void, Wrapper> {
private TextView textView;
public GetWeatherTask(TextView textView) {
this.textView = textView;
}
#Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
String Temperature = "x";
String city = "y";
String country = "z";
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject cityobj = topLevel.getJSONObject("city");
Temperature = String.valueOf(main.getDouble("temp"));
city = cityobj.getString("name");
country = cityobj.getString("country");
w.Temperature= Temperature;
w.city= city;
w.country=country;
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}
#Override
protected void onPostExecute(Wrapper w) {
textView.setText("Current Temperature: " + w.Temperature + " C" + (char) 0x00B0
+"\n" + "Current Location: "+ w.country +"\n" + "City: "+ w.city );
}
}
}
UPDATE:
turned out that that I was using the wrong url in my code,I was using :
http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s
Instead I should've been using:
http://api.openweathermap.org/data/2.5/forecast?lat=%f&lon=%f&units=%s&appid=%s
-aka instead of weather I should've been using forcast
Your error starts here
JSONObject main = topLevel.getJSONObject("main");
Probably because the topLevel object has no "main" key.
{
"city":{ },
"cod":"200",
"message":0.1859,
"cnt":40,
"list":[ ]
}
Throw your JSON into here. https://jsonformatter.curiousconcept.com/
You'll notice that there are many, many "main" keys that are within the "list" element, but you have to parse those starting from getJSONArray("list").
Basically, something like this
String city = "undefined";
String country = "undefined";
List<Double> temperatures = new ArrayList<Double>();
try {
JSONObject object = new JSONObject(builder.toString());
JSONObject jCity = object.getJSONObject("city");
city = jCity.getString("name");
country = jCity.getString("country");
JSONArray weatherList = object.getJSONArray("list");
for (int i = 0; i < weatherList.length(); i++) {
JSONObject listObject = weatherList.getJSONObject(i);
double temp = listObject.getJSONObject("main").getDouble("temp");
temperatures.add(temp);
}
} catch (JSONException e) {
e.printStackTrace();
}
return new Wrapper(city, country, temperatures);
After studying your code, either your try block is failing, which is returning your object, but empty, or there is something wrong with your JSON parsing. If you could show us the JSON you are trying to parse that would be a great help.
That being said, the fact that it is still showing as "UNDEFINED" is because that is how you initialised it, and becuase (the JSON parse is likely failing), the object is being returned in an un-edited state.
EDIT:
You are parsing the JSON wrong. You are trying to find an object called "main" in the top directory, however the main object only exists inside of an array called list!
Please look here for a more easy to see and visual representation: http://prntscr.com/dlhlrk
You can use this site to help visualise your JSON and create an appropriate soluton based upon it. https://jsonformatter.curiousconcept.com/
Looking at the API you posted earlier (api.openweathermap.org) you are trying to access variables that don't exist. I suggest you have a look at what the API returns and try getting the variables one by one if you are getting a JSONException
EDIT:
What API you are using? In your initial post you said it was http://api.openweathermap.org/data/2.5/weather but in a comment above you said it was http://api.openweathermap.org/data/2.5/forecast.
If you're using the weather API (as initially stated) you can use the below:
#Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
Log.d("JSON", builder.toString());
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject sys = topLevel.getJSONObject("sys");
w.Temperature = String.valueOf(main.getDouble("temp"));
w.city = topLevel.getString("name");
w.country = sys.getString("country");
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}

Converting json from a file to a java object

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.

IllegalArgumentException JSON

I am trying to put String[] in jsonObject and getting following error
java.lang.IllegalArgumentException: Invalid type of value. Type:
[[Ljava.lang.String;] with value: [[Ljava.lang.String;#189db56] at
com.ibm.json.java.JSONObject.put(JSONObject.java:241)
Please help me to resolve this.
Thanks
public JSONObject toJSONObject() {
JSONObject jsonObject = new JSONObject();
//Use reflection to get a list of all get methods
//and add there corresponding values to the JSON object
Class cl = dto.getClass();
logger.infoFormat("Converting {0} to JSON Object", cl.getName());
Method[] methods = cl.getDeclaredMethods();
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith("get")) {
logger.infoFormat("Processing method - {0}", methodName);
//Check for no parameters
if (method.getParameterTypes().length == 0) {
String tag = getLabel(method);
Object tagValue = new Object();
try {
tagValue = method.invoke(dto);
} catch (Exception e) {
logger.errorFormat("Error invoking method - {0}", method.getName());
}
if (method.getReturnType().isAssignableFrom(BaseDTO.class)) {
DTOSerializer serializer = new DTOSerializer((BaseDTO) tagValue);
jsonObject.put(tag, serializer.toJSONObject());
} else if (method.getReturnType().isAssignableFrom(List.class)) {
ListSerializer serializer = new ListSerializer((List<BaseDTO>) tagValue);
jsonObject.put(tag, serializer.toJSONArray());
} else {
if (tagValue != null) jsonObject.put(tag, tagValue);
}
}
}
}
return(jsonObject);
}
try
jsonObject.put("yourKey", Arrays.asList(yorStringArray));
As you should read the manual first http://www.json.org/javadoc/org/json/JSONObject.html there is no variation of it expects an Object[]
Maybe you should take a look at google-gson.
I like it very much to work with json in Java.

Categories