gson with mixed read - java

I'm trying to read json with gson, but I can't get a "simple" gson example to work.
From: https://sites.google.com/site/gson/streaming
public List<Message> readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
List<Message> messages = new ArrayList<Message>();
reader.beginArray();
while (reader.hasNext()) {
Message message = gson.fromJson(reader, Message.class);
messages.add(message);
}
reader.endArray();
reader.close();
return messages;
}
Here's the problem, if I try with:
JsonReader reader;
Gson gson = new Gson();
gson.fromJson(reader,Program.class);
It doesn't even build.
The method fromJson(String, Class<T>) in the type Gson is not applicable for the arguments (JsonReader, Class<Program>)
There seems to be a method according to eclipse:
fromJson(JsonReader arg0, Type arg1)

Replace
import android.util.JsonReader;
with
import com.google.gson.stream.JsonReader
did it! =)

It is mentionned that the fromJson method accepts argument 0 as a String. Try to create a method that transforms the inputStream to a String.
static public String generateString(InputStream stream) {
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader buffer = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
try {
String cur;
while ((cur = buffer.readLine()) != null) {
sb.append(cur).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}

Related

when accessing Json file in jar (java.lang.NullPointerException)

I need to access some data that it stored in a Json file that is in Resources file. The code compiles in eclipse but when I try to Export and run as JAR file I get this exception:
The location of the Json file is:
I tried to use:
Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AutomationJson.json");
or
Thread.currentThread().getContextClassLoader()
.getResourceAsStream("/AutomationJson.json");
Main(){
InputStream jsonFileStream = getClass().getClassLoader().getResourceAsStream("AutomationJson.json");
String jsonString = readFromJARFile();
jsonData();
}
private void jsonData() {
JsonNode node = null;
try {
node = JsonHelper.parse(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
secondUserName = node.get("secondUserName").asText();
password = node.get("password").asText();
}
public String readFromJARFile() throws IOException {
InputStreamReader isr = new InputStreamReader(jsonFileStream);
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
isr.close();
return sb.toString();
}
The Json helper class:
public class JsonHelper {
private static ObjectMapper objectMapper = getDefaultMapper();
static ObjectMapper getDefaultMapper() {
ObjectMapper defaultMapper = new ObjectMapper();
defaultMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return defaultMapper;
}
public static JsonNode parse(String src) throws JsonProcessingException {
return objectMapper.readTree(src);
}
}

GSON Adding java object to json array

I have json {"name": "John", "tests":["apple"]}. In my Java code I want to update this json throught gson - add string field to json array and save to file to have this json - {"name": "John", "tests":["apple", "pinapple"]}. So is there a way how ? Java class for my json look like this:
public class Test{
private String name;
private List<String> tests;
// Getters/Setters
}
Reading json in java like this:
Gson gson = new Gson();
try (Reader reader = new FileReader("D:\\file.json")) {
Test js = gson.fromJson(reader, Test.class);
System.out.println(js.getName());
} catch (IOException e) {
e.printStackTrace();
}
Doing this my new json file is empty:
Gson gson = new Gson();
try (Reader reader = new FileReader("D:\\file.json")) {
Test test = gson.fromJson(reader, Test.class);
System.out.println(test.getName());
test.getTests().add("pinapple");
String newJson = gson.toJson(test);
System.out.println(newJson);
gson.toJson(test, new FileWriter("D:\\file.json"));
} catch (IOException e) {
e.printStackTrace();
}
Test test = gson.fromJson(reader, Test.class);
Once you have your Test object do:
test.getTests().add("pineapple");
Now you have the pineapple in your array. You can make your JSON string:
String newJson = gson.toJson(test);
System.out.println(newJson);
or write it back in the same file
gson.toJson(test, new FileWriter("D:\\file.json"));
EDIT: Whole code
String fileName = "D:\\file.json";
Gson gson = new Gson();
Test test = null;
try (Reader reader = new FileReader(fileName)) {
test = gson.fromJson(reader, Test.class);
} catch (IOException e) {
e.printStackTrace();
}
test.getTests().add("pineapple");
String newJson = gson.toJson(test);
System.out.println(newJson);
try (Writer writer = new FileWriter(fileName)) {
gson.toJson(test, writer);
}

FileUtils.readFileToString() from Apache Commons IO works incorrectly with Cyrillic

I am using FileUtils.readFileToString to read contents of a text file with JSON at once. The file is UTF-8 encoded (w/o BOM). Yet, instead of cyrillic letters I get ?????? signs. Why?
public String getJSON() throws IOException
{
File customersFile = new File(this.STORAGE_FILE_PATH);
return FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8);
}
FileUtils.readFileToString doesn't work with StandardCharsets.UTF_8.
Instead, try
FileUtils.readFileToString(customersFile, "UTF-8");
or
FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8.name());
This is how I solved it back in 2015:
public String getJSON() throws IOException
{
// File customersFile = new File(this.STORAGE_FILE_PATH);
// return FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8);
String JSON = "";
InputStream stream = new FileInputStream(this.STORAGE_FILE_PATH);
String nextString = "";
try {
if (stream != null) {
InputStreamReader streamReader = new InputStreamReader(stream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
while ((nextString = reader.readLine()) != null)
JSON = new StringBuilder().append(JSON).append(nextString).toString();
}
}
catch(Exception ex)
{
System.err.println(ex.getMessage());
}
return JSON;
}
I figured out that in logs all was fine, so I solved problem in rest controller:
#GetMapping(value = "/getXmlByIin", produces = "application/json;charset=UTF-8")

Parsing Multiple JSON Strings to Objects using json-simple

I have a socket server running, which will emit json strings for clients. I tried to use json-simple for parsing them. But, the problem I face is that, the server doesn't have any delimiter character to segregate json strings. So, my json-simple JSONParser throws ParseException.
As an alternate, I tried to use json-smart. But, in this case, the JSONParser returns only the first object and ignores rest of the string.
I'm new to this json parsing stuff. It would be great if people can direct me to correct way of handling json string streams.
Edit: - Adding JSON String and Sample Code
{"type":"response","id":"1","result":[true,0]}{"type":"response","id":"2","result":[true,1]}
Currently this method returns the single object when I use json-smart and null when json-simple is used.
public JSONObject getResponse(JSONObject request) {
String s = null;
Socket soc = null;
PrintWriter sout = null;
BufferedReader sin = null;
try {
soc = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
sout = new PrintWriter(soc.getOutputStream());
sin = new BufferedReader(
new InputStreamReader(soc.getInputStream()));
sout.println(request.toJSONString());
sout.flush();
s = sin.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
sin.close();
sout.close();
soc.close();
} catch (Exception e) {
}
}
Object response = null;
try {
response = JSONValue.parseWithException(s.toString());
}catch (ParseException e){
e.printStackTrace();
}
return (JSONObject) response;
Thanks in advance,
Kaja
I have found a solution using Jackson. Here is the code that worked for me.
MappingJsonFactory factory = new MappingJsonFactory();
JsonParser parser = factory.createParser(soc.getInputStream());
JsonToken curToken = parser.nextToken();
if (curToken != JsonToken.START_OBJECT) {
System.err.println("Not in start object!, Exiting...");
return null;
}
while (runParser.get() == true) {
if (curToken == JsonToken.START_OBJECT) {
TreeNode node = parser.readValueAsTree();
System.out.println(node.getClass().getName());
System.out.println(node);
}
curToken = parser.nextToken();
}
Thanks Kaja Mohideen! It's working with a small change in while loop.
This code works perfectly. In my case input json is in file.
libs used : jackson-core, jackson-annotation and jackson-databind
MappingJsonFactory factory = new MappingJsonFactory();
JsonParser parser = null;
File file = new File("jsontest.txt");
try {
parser = factory.createParser(file);
JsonToken curToken = parser.nextToken();
if (curToken != JsonToken.START_OBJECT) {
System.err.println("Not in start object!, Exiting...");
}
while (parser.hasCurrentToken()) {
if (curToken == JsonToken.START_OBJECT) {
TreeNode node = parser.readValueAsTree();
System.out.println(node);
}
curToken = parser.nextToken();
}
} catch (JsonParseException e) {
e.printStackTrace();
}

Parsing ical format - Parse exception

I am using ical4j to parse the ical format on the Android.
My input ics is:
BEGIN:VCALENDAR
BEGIN:VEVENT
SEQUENCE:5
DTSTART;TZID=US/Pacific:20021028T140000
DTSTAMP:20021028T011706Z
SUMMARY:Coffee with Jason
UID:EC9439B1-FF65-11D6-9973-003065F99D04
DTEND;TZID=US/Pacific:20021028T150000
END:VEVENT
END:VCALENDAR
But when I try to parse this I get the exception:
Error at line 1: Expected [VCALENDAR], read [VCALENDARBEGIN]
The relevant code is:
HttpHelper httpHelper = new HttpHelper(
"http://10.0.2.2/getcalendar.php", params);
StringBuilder response = httpHelper.postData();
StringReader sin = new StringReader(response.toString());
CalendarBuilder builder = new CalendarBuilder();
Calendar cal = null;
try {
cal = builder.build(sin);
} catch (IOException e) {
Log.d("calendar", "io exception" + e.getLocalizedMessage());
} catch (ParserException e) {
Log.d("calendar", "parser exception" + e.getLocalizedMessage());
}
public class HttpHelper {
final HttpClient client;
final HttpPost post;
final List<NameValuePair> data;
public HttpHelper(String address, List<NameValuePair> data) {
client = new DefaultHttpClient();
post = new HttpPost(address);
this.data = data;
}
private class GetResponseTask extends AsyncTask<Void, Void, StringBuilder> {
protected StringBuilder doInBackground(Void... arg0) {
try {
HttpResponse response = client.execute(post);
return inputStreamToString(response.getEntity().getContent());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
}
public StringBuilder postData() {
try {
post.setEntity(new UrlEncodedFormEntity(data));
return (new GetResponseTask().execute()).get();
} catch (UnsupportedEncodingException e) {
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
return null;
}
private StringBuilder inputStreamToString(InputStream is)
throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
Log.v("debug", "Line: " + line);
}
// Return full string
return total;
}
}
My guess would be the line endings in the response string are different from what ical4j expects.
The standard specifies you should use CRLF (aka '\r\n').
The input file is valid, the problem is with your method inputStreamToString(), which performs a readLine() on the input (which strips the newlines) and appends to a string without re-adding the newlines.
I would suggest either to use an alternative to readLine() (if you want to preserve newlines from the original file), or append your own newlines in the loop, eg:
while ((line = rd.readLine()) != null) {
total.append(line);
total.append("\r\n");
Log.v("debug", "Line: " + line);
}

Categories

Resources