Java: Json schema generator (for string orJSONObject) - java

Are there any libraries to convert JSON in String/jackson/org.JSON.JSONOBJECT/etc... to a JSON schema?
So far, the only generator I found covert Java classes to JSON schemas. I'm about to write my own converted, but it'd be nice if I didn't have to re-invent the wheel.

looks like there isn't. I had to write my own generator.

Yes there is: https://github.com/java-json-tools/json-schema-validator. It ingests Jacson's JsonNode containing the schema definition and can validate JSON data against that schema.

You can use GSON library.
Convert Java object to JSON:
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON, and save into a file
gson.toJson(obj, new FileWriter("D:\\file.json"));
// 2. Java object to JSON, and assign to a String
String jsonInString = gson.toJson(obj);
Convert JSON to Java object:
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'foo'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);

Related

Java: Extract json values as individuals

I have this json in java:
jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}
jsonObj is response from an API, so I have it as jsonObject and I don't read it from any file.
Is there an easy way to extract all the values as individuals like jsonObj [1]?
You may Use Gson parsing library as below :
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);
Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);
or simply use:
example
JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse = object.getString("getIMEIResult");
for Array use :
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
You should use a library to deserialize your JSON in a Java Object.
Libraries like GSON, Genson or Jackson.
Once you transform the json in a object, it will have a property called "ps" that will be an array (or a List)

How to extract single key and convert to class using GSON

Here is my json:
{
"timestamp":"04295d4f-2a6f-4a38-a818-52108cbdc358",
"lastFullSyncDate":null,
"ftpInfo":null,
"listingInfo":{
"itemID":"110179365615",
"itemTitle":"test",
"itemPrice":"88.2235294117647",
.......
....
.....
}
}
I have a java class named listingInfo was trying to use gson to convert the string with the key of listingInfo to the class, but i'm getting nulls for all the vars.
Gson gson = new Gson();
gson.fromJson(json, ListingInfo.class);
While trying to convert to the part class which contains the time stamp and etc i dot get the vars but the listingInfo is null inside
Is it possible to get into the nested key and only convert him to the class?
You can do it by parsing whole json tree and then extracting the nested key
String json = ...; //your json string
Gson gson = new Gson();
JsonElement element = new JsonParser().parse(json); //parse to json tree
JsonElement listingElement = element.getAsJsonObject().get("listingInfo"); // extract key
ListingInfo listingInfo = gson.fromJson(listingElement, ListingInfo.class);

Java Parse String

I have a String in a following format:
{"id":"1263e246711d665a1fc48f09","facebook_username":"","google_username":"814234576543213456788"}
but sometimes this string looks like:
{"id":"1263e246711d665a1fc48f09","facebook_username":"109774662140688764736","google_username":""}
How can I extract those values if I do not know the index of substrings as they will change for different cases?
That looks like json format, you should give a look to the Gson library by google that will parse that string automatically.
Your class should look like this
public class Data
{
private String id;
private String facebook_username;
private String google_username;
// getters / setters...
}
And then you can simply create a function that create the object from the json string:
Data getDataFromJson(String json){
return (Data) new Gson().fromJson(json, Data.class);
}
That String is formated in JSON (JavaScript Object Notation). Is a common language used to transfer data.
You can parse it using Google's library Gson, just add it to your class path .
Gson gson = new Gson();
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class); //The object you want to convert to.
https://github.com/google/gson
Check this out on how to convert to Java Object
Parsing as JSON notwithstanding, here's a pure string-based solution:
String id = str.replaceAll(".*\"id\":\"(.*?)\".*", "$1");
And similar for the other two, swapping id for the other field names.

Get JSON values to form an Object

Using GSON :
Gson gson = new Gson();
String json = gson.toJson(response);
System.out.println(json);
I receive the following JSON representation of a User:
"{\"userID\":\"user2\",\"firstName\":\"Maria\",\"lastName\":\"Silva\",\"birthDate\":\"Ago 1, 2012\",\"gender\":\"Female\"}"
Now, I want to get those values to construct a User object (doing User.setuserID, userObj.setFirstName, ... )
How can I get the correspond values to set the User values?
Gson will do that for you. You need not worry about it. That's the power of Gson.
User object = gson.fromJson(jsonString, User.class); // Fully populated User object.

Possibility of using Generic function to convert any Java Object to JSON

I would like to know if it is possible to convert any Java object to JSON object. Currently I have the following code.
JSONArray data = new JSONArray();
for (User user : users) {
JSONArray row = new JSONArray();
row.put(user.getId()).put(user.getUserName()).put(user.isEnabled());
data.put(row);
}
The current issue is different object (e.g. User and Admin) will have different property, thus the above code will work for other object. I am thinking of putting a similar code in my GenericHibernateDAO in order to automatically convert any list into a json list.
You can serialize your java object to json object. There are n number of library is available ex gson, jettyson, flexjson etc.
GSON example -
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);
(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]
Here i exemplify the way of converting POJO to json using jackson
create your pojo : User user = new User();
you can set or get values to/from user
create ObjectMapper : ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);// object to json

Categories

Resources