JSON Schema Validation With typecasting feature - java

Please suggest how to perform typecasting before validation of JSON Schema in Java. I've achieved the same in NodeJS using json-schema-validation-pipeline package. Below code snippet for reference (where param1 was actually of type string as provided from backend API).
var ValidationPipeline = require('json-schema-validation-pipeline');
var V = ValidationPipeline.V;
var validate = ValidationPipeline([
{
$schema: {
'param1': V(Number).min(60)
}
},
{ $cast: { param1: Number } }
]);
So basically, I am looking for equivalent solution in Java for above code snippet. Thanks

Assign it to POJO model class of JAVA and once you have this native object then you can typecast to anything as its in language operation For example-
File file = new File("json/student.json");
// get json as buffer
BufferedReader br = new BufferedReader(new FileReader(file));
// obtained Gson object
Gson gson = new Gson(); //import com.google.gson.Gson;
// called fromJson() method and passed incoming buffer from json file
// passed student class reference to convert converted result as Student object
Student student = gson.fromJson(br, Student.class);

Related

How to parse prettyprinted JSON with GSON

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.

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

Converting JSON objects in Android with gson

I am new to Java and Android so please bear with me. I am trying to create a function which calls a wcf service and converts the returned result from JSON to a Java object (I pass the type as the object t), but it's throwing a null pointer exception on t, which must be null as I just want to pass an object of the correct type so that it becomes filled when converted. Kindly help me with it.
public static String Post(String serviceURL, Map<String, String> entites,
Class<?> t) {
String responseString = "";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Gson gson = new GsonBuilder().create();
//now we will try to convert the class to the specified type.
t = (Class<?>) gson.fromJson(responseString, t);
} catch (Exception e) {
responseString = e.toString();
}
return responseString;
Thanks a lot.
After some tries, I ended up with this code but I am still facing a null pointer exception.
MemberInfo mem = new MemberInfo();
TypeToken<MemberInfo> m = null ;
ServiceCaller.Post(getString(R.string.LoginService), values , m);
Gson gson = new GsonBuilder().create();
//now we will try to convert the class to the specified type.
t = (TypeToken<T>) gson.fromJson(responseString, (Type) t);
As far as I know, this is impossible. In order for one to do this, gson would have to be able to detect the correct class only from the serialized string. However, a single string can be interpreted in many valid ways. For instance, take an example on the gson website:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
BagOfPrimitives() {
// no-args constructor
}
}
Using Gson.toJson on an instance of this class results in the string:
{"value1":1,"value2":"abc"}
However, if I made another class identical to the first in all respects but name:
class SackOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
SackOfPrimitives() {
// no-args constructor
}
}
Then this would also serialize to the same string:
{"value1":1,"value2":"abc"}
My point is that given a single string like {"value1":1,"value2":"abc"}, there is no way for gson to determine whether it should deserialize it into an object of type BagOfPrimitives or type SackOfPrimitives. Therefore, you always have to provide gson with the correct type, because it wouldn't be possible for gson to figure it out by itself.

How to convert String to Json

I have a servlet in Java and I would like to know how I can do the following.
I have a String variable with the value of a name and want to create a Json with the variable being something like {"name": "David"}.
How do I do this?
I have the following code but I get an error :
Serious: Servlet.service () for servlet threw
exception servlet.UsuarioServlet java.lang.NullPointerException
at servlet.UsuarioServlet.doPost (UsuarioServlet.java: 166):
at line
String myString = new JSONObject().put("name", "Hello, World!").toString();
Your exact problem is described by Chandra.
And you may use the JSONObject using his suggestion.
As you now see, its designers hadn't in mind the properties, like chaining, which made the success of other languages or libs.
I'd suggest you use the very good Google Gson one. It makes both decoding and encoding very easy :
The idea is that you may define your class for example as :
public class MyClass {
public String name = "Hello, World!";
}
private Gson gson = new GsonBuilder().create();
PrintWriter writer = httpServletResponse.getWriter();
writer.write( gson.toJson(yourObject));
The json library based on Map. So, put basically returns the previous value associated with this key, which is null, so null pointer exception.( http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html#put%28java.lang.Object,%20java.lang.Object%29)
You can rewrite the code as follows to resolve the issue.
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name", "Hello, World");
String myString = jsonObject1.toString();
I tried with GSON, GSON is directly convert your JSONString to java class object.
Example:
String jsonString = {"phoneNumber": "8888888888"}
create a new class:
class Phone {
#SerializedName("phoneNumber")
private String phoneNumebr;
public void setPhoneNumber(String phoneNumebr) {
this.phoneNumebr = phoneNumebr;
}
public String getPhoneNumebr(){
return phoneNumber;
}
}
// in java
Gson gson = new Gson();
Phone phone = gson.fromJson(jsonString, Phone.class);
System.out.println(" Phone number is "+phone.getPhoneNumebr());

Categories

Resources