How to parse prettyprinted JSON with GSON - java

I'm connecting to some APIs. These calls return an already "prettyprinted" JSON instead of a one-line JSON.
Example:
[
{
"Field1.1": "Value1.1",
"Field1.2": "value1.2",
"Field1.3": "Value1.3"
},
{
"Field2.1": "Value2.1",
"Field2.2": "value2.2",
"Field2.3": "Value2.3"
}
]
When I try to parse a JSON like this with GSON it throws JsonSyntaxException.
Code example:
BufferedReader br = /*Extracting response from server*/
JsonElement jelement = new JsonParser().parse(br.readLine())
Is there a way to parse JSON files formatted like this?
EDIT:
I tried using Gson directly:
BufferedReader jsonBuf = ....
Gson gson = new Gson();
JsonObject jobj = gson.fromJson(jsonBuf, JsonObject.class)
But jobj is NULL when the code terminates.
I also tried to parse the string contained into the BufferedReader into a single line string and then using JsonParser on that:
import org.apache.commons.io.IOUtils
BufferedReader jsonBuf = ....
JsonElement jEl = new JsonParser().parse(IOUtils.toString(jsonBuf).replaceAll("\\s+", "");
But the JsonElement I get in the end is a NULL pointer...
I can't understand what I'm doing wrong...

BufferedReader::nextLine reads only one line. Either you read whole json from your reader to some String variable or you will use for example Gson::fromJson(Reader, Type) and pass reader directly to this method.
As your json looks like an array of json objects it can be deserialized to List<Map<String,String>> with usage of TypeToken :
BufferedReader bufferedReader = ...
Type type = new TypeToken<List<Map<String,String>>>(){}.getType();
Gson gson = new Gson();
List<Map<String,String>> newMap = gson.fromJson(bufferedReader, type);
You could also use some custom object instead of Map depending on your needs.

Related

JSONObject (org.json) to JsonElement(com.google.gson)

I am writing a java code in which i need to convert a JSONObject to JsonElement.Is there any way using which i can convert a JSONObject (org.json) to JsonElement(com.google.gson)?
One way that always works is to serialize the object to JSON and then parse it again:
JSONObject myData = ...
Gson gson = new Gson();
JsonElement element = gson.fromJson(myData.toString(), JsonElement.class);

Converting a string in JSON object and validating

I am trying to validate this string below. Actually I am receiving this string in my servlet, now I need to validate these values at backend. What is the right way to do so. Shall I first convert it to JSON Object then to HashMap? Please suggest the correct/appropriate approach to be used here. I am quite new to Java and JSON.
String is
"{"if_ack":4},{"if_cmd":1,"if_state":1},{"if_cmd":1,"if_state":5}"
I am using GSON for processing JSON at server. For example:
InputStream is (send by client, JSON format)
Reader reader = new InputStreamReader(is);
Gson gson = new Gson();
List<YourClass> items = gson.fromJson(reader, new TypeToken<List<YourClass>>()
YourClass should have attributes like if_ack, if_state, if_cmd,...
Then you use as simple as this:
for (YourClass item : items) {
//do whatever you want
}
EDIT: your string should be in correct JSON format like this (JSON array): [{"if_ack":4}, {"if_cmd":1,"if_state":1}, {"if_cmd":1,"if_state":5}]
EXAMPLE:
You have JSON like this : [{"id": "1", "image": "test1"}, {"id": "2", "image": "test2"}]
YourClass.java should be:
public class YourClass{
private int id;
private String image;
//+ constructor, getters, setters,...
}
On server you can receive JSON from client side by InputStream is:
Reader reader = new InputStreamReader(is, "UTF-8");
Gson gson = new Gson();
List<YourClass> items = gson.fromJson(reader, new TypeToken<List<YourClass>>();
and then:
for (YourClass item: items){
//acces to item properties like item.id, item.image
}

Parsing DBpedia JSON from localhost extraction server in java when the schema isn't known

This is probably a quick answer to a very novice question. I am having trouble wrapping my head around how to get JSON text dbpedia extraction server running from a localhost. The server is running fine, I followed the official instructions.
I have read the other StackOverflow questions about parsing JSON in java and what I am having trouble understanding is how to parse the JSON when the schema or structure is unknown.
For example in my code I try to grab the JSON from localhost and put it into a java object. But all the examples of parsing JSON online use a predesigned java object and all the JSON keys are mapped to an object's fields. (ie Employee class: name,job,email,id,phone)
String sURL = "http://localhost:9999/server/extraction/en/extract?title=" + wikipage + "&revid=&format=rdf-json&extractors=custom"; //just a string
URL url = new URL(sURL);
Reader pageReader = new InputStreamReader(url.openConnection().getInputStream());
Gson g = new Gson();
JsonReader jr = new JsonReader(new InputStreamReader((InputStream) request.getContent()));
jr.setLenient(true);
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
I now have this "json object" for the film "Blue Velvet" I can parse/iterate with jr.hasNext() or rootobj.getAsJsonArray().
Am I going about this correctly?
I feel like I am reinventing the wheel. Is there a standard way of parsing DBpedia JSON objects in Java?
At least the Jackson JSON library allows you to parse incoming JSON into a Map. If the keys and values of the JSON can be of any type, then you need to use Map<Object, Object>, which is a bit cumbersome, but anyways this should work:
ObjectMapper mapper = new ObjectMapper();
Map<Object, Object> parsedJSON = mapper.readValue(incomingJSON,
mapper.getTypeFactory().constructMapType(
LinkedHashMap.class,
Object.class,
Object.class));

How to have each record of JSON on a separate line?

When I use JSONArray and JSONObject to generate a JSON, whole JSON will be generated in one line. How can I have each record on a separate line?
It generates like this:
[{"key1":"value1","key2":"value2"}]
I need it to be like following:
[{
"key1":"value1",
"key2":"value2"
}]
You can use Pretty Print JSON Output (Jackson).
Bellow are some examples
Convert Object and print its output in JSON format.
User user = new User();
//...set user data
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
Pretty Print JSON String
String test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"myname\"}";
Object json = mapper.readValue(test, Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
Reference : http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/
You may use of the google-gson library for beautifying your JSON string.
You can download the library from here
Sample code :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);
OR
you can use org.json
Sample code :
JSONTokener tokener = new JSONTokener(uglyJsonString); //tokenize the ugly JSON string
JSONObject finalResult = new JSONObject(tokener); // convert it to JSON object
System.out.println(finalResult.toString(4)); // To string method prints it with specified indentation.
Refer answer from this post :
Pretty-Print JSON in Java
The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
and please refer this : https://stackoverflow.com/a/2614874/3164682
you can also beautify your string online here.. http://codebeautify.org/jsonviewer
For gettting a easy to read json file you can configure the ObjectMapper to Indent using the following:
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

Writing to a json file is not in correct format

I am creating a java project which writes data to an already existing json file.I am using gson libraries to write.The problem is when i write the json it written at the end of the file not inside.Here is my json before i run the program
{
"trips":[
{
"tripname":"Goa",
"members":"john"}
]
}
here is my java code
FileOutputStream os=new FileOutputStream(file,true);
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
Gson gson=new GsonBuilder().setPrettyPrinting().create();
String temp=gson.toJson(trips);
bw.append(temp);
bw.close();
and here is my output json
{
"trips":[
{
"tripname":"Goa",
"members":"john"}
]
}{
"tripname": "trip1",
"members": "xyzxyz"
}
the newly added must be inside the trips array how can i achieve it.
The problem is that you are not using Gson. You need to have Java Bean with proper Gson annotaions and with this use Gson to serialize.
Look at this example: https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples
Edit
More or less it would look like this:
public class Trip implements Serializable {
private String tripName;
private String members;
// getters setters
}
Using Gson:
List<Trip> trips = new ArrayList<>();
// add to list
Gson gson = new Gson();
// to json
String json = gson.toJson(trips)
// from json
Type collectionType = new TypeToken<Collection<Trip>>(){}.getType();
List<Trip> trips2 = gson.fromJson(json, collectionType);

Categories

Resources