Why am I getting Json Malformed Exception? - json

I'm trying to make a program using json to save user registers to file, but when I try to read my json I get the error "JSON malformed". This is my code to write in json:
Gson gsonObject = new Gson();
FileWriter writerFile;
try {
writerFile = new FileWriter("users.json", true);
writerFile.write(gsonObject.toJson(writerUser));
writerFile.close();
} catch (IOException e) {
e.printStackTrace();
}
I use arrays to be easy modify the values (only take the json back to array and make my modify) but i can't reader this json file after writer, this is my reader code:
Gson gson = new Gson();
List<User> userList;
try {
BufferedReader readerUserList = new BufferedReader(new FileReader("users.json"));
userList = Arrays.asList(gson.fromJson(readerUserList, User[].class));
for (User user : userList) {
System.out.println(user.toString());
}
And after that i get "json malformed" error, where is my error?
If help you guys, inside my json file is my arrays like that:
[{"name":"james","idCode":1}][{"name":"kyle","idCode":2}][{"name":"test","idCode":3}]

I've never used Gson... but your json file has format problems, it is supposed to look like this:
[{"name":"james","idCode":1},{"name":"kyle","idCode":2},{"name":"test","idCode":3}]
The problem is not when you try to read, but when you write it.

Related

how to read file stored in local drive using Xtend

how to read a json file using Xtend and using MydslGenrator ,use those file in eclipse editor
First thing MydslGenrator is used to generate the code from your DSL. If you want to generate code with using JSON file use below code in MydslGenrator file
override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) {
try
{
URL url;
url = new URL("platform:/plugin/yourpackgename/foldername/yourJsonFile_Name.json");
try {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(url.openStream()));
reader.beginObject();
// get your JsonObject from reader object.
// do your work here
}`

how to do json parser in android using json structure

I have json structure like as shown in image. How should I use jsonparser for this?
Use like this
String data;//your entire JSON data as String
try {
JSONObject object = new JSONObject(data);
String status = object.getString("status");
String response = object.getString("response");
} catch (JSONException e) {
e.printStackTrace();
}
Create Model class like your JSON
and use GSON library to parse your json into model.

Input Stream from MongoDB in JSP

I'm trying to write a method that takes a JSON object that is stored in a mongoDB and serves a ical/ics file to the user.
This is my code so far:
#RequestMapping(value = "/ical", method = RequestMethod.GET)
public void getIcalFile(
String json,
HttpServletResponse response) {
try {
// get your file as InputStream
InputStream is = //Input stream from JSON. HOW?
// copy it to response's OutputStream
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
//log.info("Error writing file to output stream. Filename was '" + fileName + "'");
throw new RuntimeException("IOError writinethod that takes a JSON object and serves a ical/ics file to the user. This is my code so far:g file to output stream");
}
}
I have no idea how to take an JSON object and use it as an input stream. If there is a better way to do what I am trying to achieve, I would love a suggestion.

How does play.libs.Json.fromJson handled a List<T> in Java?

I'd like to use the Json library that comes with the play 2.1 framework.
But I'm stuck with deserializing a json object back into a java List.
With gson, you can write s.th. like
Type type = new TypeToken<List<XYZ>>(){}.getType();
List<XYZ> xyzList = gson.fromJson(jsonXyz, type);
Is there a way to do the same with play.libs.Json.fromJson ?
Any help appreciated.
Edit (17.12.2013):
I did the following to work around the problem. I guess there is a better way, but I didn't found it.
List<MyObject> response = new ArrayList<MyObject>();
Promise<WS.Response> result = WS.url(Configuration.getRestPrefix() + "myObjects").get();
WS.Response res = result.get();
JsonNode json = res.asJson();
if (json != null) {
for (JsonNode jsonNode : json) {
if (jsonNode.isArray()) {
for (JsonNode jsonNodeInner : jsonNode) {
MyObject mobj = Json.fromJson(jsonNodeInner, MyObject.class);
response.add(bst);
}
} else {
MyObject mobj = Json.fromJson(jsonNode, MyObject.class);
response.add(bst);
}
}
}
return response;
The Json library for Play Java is really just a thin wrapper over the Jackson JSON library (http://jackson.codehaus.org/). The Jackson way to deserialize a list of custom objects is mentioned here.
For your case, once you parse the json from the response body, you would do something like this, assuming MyObject is a plain POJO:
JsonNode json = res.asJson();
try{
List<MyObject> objects = new ObjectMapper().readValue(json, new TypeReference<List<MyObject>>(){});
}catch(Exception e){
//handle exception
}
I'm assuming you were asking about Play Java based on your edit, Play Scala's JSON library is also based on Jackson but has more features and syntactic sugar to accommodate functional programming patterns.
You can use the following code:
List<YourClass> returnedRoles = new ObjectMapper().readValue(jsonString
,TypeFactory.defaultInstance().constructCollectionType(List.class,
YourClass.class));

Retrieving JSON Object Literal from HttpServletRequest

I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.
Any insight is appreciated.
Thanks.
are you looking for this ?
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
System.out.println(sb.toString());
}
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:
BufferedReader reader = request.getReader();
Gson gson = new Gson();
MyBean myBean = gson.fromJson(reader, MyBean.class);
There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON or other object with Gson, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..
If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.
Converting the retreived data from the request object to json object is as below using google-gson
Gson gson = new Gson();
ABCClass c1 = gson.fromJson(data, ABCClass.class);
//ABC class is a class whose strcuture matches to the data variable retrieved