Interpolate JSON values into a string - java

I am writing an application/class that will take in a template text file and a JSON value and return interpolated text back to the caller.
The format of the input template text file needs to be determined. For example: my name is ${fullName}
Example of the JSON:
{"fullName": "Elon Musk"}
Expected output:
"my name is Elon Musk"
I am looking for a widely used library/formats that can accomplish this.
What format should the template text file be?
What library would support the template text file format defined above and accept JSON values?
Its easy to build my own parser but there are many edge cases that needs to be taken care of and I do not want to reinvent the wheel.
For example, if we have a slightly complex JSON object with lists, nested values etc. then I will have to think about those as well and implement it.

I have always used org.json library. Found at http://www.json.org/.
It makes it really easy to go through JSON Objects.
For example if you want to make a new object:
JSONObject person = new JSONObject();
person.put("fullName", "Elon Musk");
person.put("phoneNumber", 3811111111);
The JSON Object would look like:
{
"fullName": "Elon Musk",
"phoneNumber": 3811111111
}
It's similar to retrieving from the Object
String name = person.getString("fullName");
You can read out the file with BufferedReader and parse it as you wish.
Hopefully I helped out. :)

This is how we do it.
Map inputMap = ["fullName": "Elon Musk"]
String finalText = StrSubstitutor.replace("my name is \${fullName}", inputMap)

You can try this:
https://github.com/alibaba/fastjson
Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Fastjson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Related

Reading from big json data in java

To start off, I'm pretty new in programming. I have to create an Android Weather App for a school project and I'm stuck with this big ass JSON:
JSON Data
Out of this, how would I read the temperature out of every 3 hour interval(example: 9.00-12.00 temperature: 5°C, 12.00-15.00 temperature: 7°C etc.).
So I have an Activity that displays the temperature of the entire day by three hour intervals. Since I have no experience with JSON I have no idea what the certain indexes mean, when does it increment(there are like 8 main: thingies).
DISCLAIMER: I have to use JSON, no GSON or other shortcuts, I have to parse and read certain data from this JSON. I get this JSON from open weather map API so it changes every day.
API
Use volly library for it. You can easily fetch data from json. No async task is needed, if you are using volly library.
First validate the json by going to http://jsonlint.com/. This will help you see the formatted Json string.
Next read up on Json array and Object .
Use AsynTask to get the Json into forecastJsonStr string.
Then you need to convert this forecastJsonStr into JSon object forecastJsonObj
To get weather data in "list" do something similar to
JSONArray weatherArray = forecastJson.getJSONArray("list");
Hope this helps
JSONObject receivedData = new JSONObject("The string that you get as response from the API");
JSONArray weatherList = receivedData.getJSONArray("list");
for(int i=0;i<weatherList.length();i++){
JSONObject data = weatherList.getJSONObjectAt(i);
String date_text - data.getString("dt_txt");
JSONArray weatherData = weatherList.getJSONArray("main");
for(int j=0;j<weatherData.length();j++){
// Here is where you will get all the weather stuff that you need
int temp = weatherData.getInt("temp");
// Similarly other values like temp_min, temp_max
}
}
So basically you need to parse the entire thing. In order to understand the whole structure more clearly use something like http://jsonviewer.stack.hu/ in order to view the JSON in a more clear way so that you know what you need from the JSON data better. Simple copy paste your data into there and click "Format".
JSON is just a name-value pair kind of storage if you see stored like "name":"value". Integer values don't have the "".
Remember all the JSON is stored in { } and a JSON can be nested in a JSON. So in your example if you see, the entire thing is a JSON. Within that you have a "city" key which has a value within { }. So "city" is a JSONObject.
Similarly "coord" is a JSONObject while "cod" is a String and "cnt" is an integer.
There can also be some instances where a name points to an array of JSON objects like "list" over here. JSON Arrays are signified using a [ ]. Enclosed within are JSON objects separated by comma.
Above is a very simple sample to get you started so that you get a jist of what is going on. So play around and try to extract more data from in there.
All the best and Happy Coding :)

Write to Json using libGDX

I am new to Json and libGDX but I have created a simple game and I want to store player names and their scores in a Json file. Is there a way to do this? I want to create a Json file in Gdx.files.localStorage if it doesnt exist and if it does, append new data to it.
I have checked code given at :
1>Using Json.Serializable to parse Json files
2>Parsing Json in libGDX
But I failed to locate how to actually create a Json file and write multiple unique object values (name and score of each player) to it. Did I miss something from their codes?
This link mentions how to load an existing json but nothing else.
First of all i have to say that i never used the Libgdx Json API myself. But i try to help you out a bit.
I think this Tutorial on github should help you out a bit.
Basicly the Json API allows you to write a whole object to a Json object and then parse that to a String. To do that use:
PlayerScore score = new PlayerScore("Player1", 1537443); // The Highscore of the Player1
Json json = new Json();
String score = json.toJson(score);
This should then be something like:
{name: Player1, score: 1537443}
Instead of toJson() you can use prettyPrint(), which includes linebreaks and tabs.
To write this to a File use:
FileHandle file = Gdx.files.local("scores.json");
file.writeString(score, true); // True means append, false means overwrite.
You can also customize your Json by implementing Json.Serializable or by adding the values by hand, using writeValue.
Reading is similar:
FileHandle file = Gdx.files.local("scores.json");
String scores = file.readString();
Json json = new Json();
PlayerScore score = json.fromJson(PlayerScore.class, scores);
If you have been using a customized version by implementing Json.Serializable you have implemented the read (Json json, JsonValue jsonMap) method. If you implemented it correctly you the deserialization should work. If you have been adding the values by hand you need to create a JsonValuejsonFile = new JsonValue(scores). scores is the String of the File. Now you can cycle throught the childs of this JsonValue or get its childs by name.
One last thing: For highscores or things like that maybe the Libgdx Preferences are the better choice. Here you can read how to use them.
Hope i could help.

A method to get JSON key values as a list

I have a requirement where in I have to get all the key values of a json returned now I am getting the json as a string.
String test = obj.returnJSON();
I need to get the JSON key values as a list is there any predefined method or I have just to write my own logic.
Thanks
KD
Use the JSON in Java library http://json.org/java/ or the google-gson library https://code.google.com/p/google-gson/. Either of these will parse the javascript string into an object, and you can get the keys from there.
Using the Java org.json parser you could do it as
String test = obj.returnJSON();
JSONArray keys = new JSONObject(test).names();
System.out.println(keys.getString(0)); // key1
the google library, GSON, is WAY BETTER and very useful.
I had the same problem and found the answer here
Best regards!

Simplest way to read from a JSON file in Java?

I'm relatively new to using JSON and all I really need to do read in a few key value pairs from a JSON file on the file system.
What I figured I would do is read in the file as a string and then parse it that way but it seems kind of redundant that way.
Here's what my file will be like:
{
"username" : "myname"
"domain" : "mydomain"
}
So essentially I need some help making an easy and efficient block of code to read in the key/value pairs. I've been trying to use GSON for the most part and haven't had much luck with examples I've found.
Thanks everyone
One other alternative is JSON.org, in which creating a JSON object from a JSON string requires only one line:
JSONObject jsonObject = new JSONObject(someJSONString);
When you need to access its value, use the functions that the JSONObject provides. For example,
String userName = jsonObject.getString("username");
String domainName = jsonObject.getString("mydomain");

Java object from JSON input file

Hi I have a json input file as follows,
{'Latitude':'20',
'coolness':2.0,
'altitude':39000,
'pilot':{'firstName':'Buzz',
'lastName':'Aldrin'},
'mission':'apollo 11'}
How to create a java object from the json input file.
Thanks
You can use the very simple GSON library, with the Gson#fromJson() method.
Here's an example: Converting JSON to Java
There are more than one APIs that can be used. The simplest one is JSONObject
Just do the following:
JSONObject o = new JSONObject(jsonString);
int alt = o.getInt("altitude");
....
there are getXXX methods for each type. It basically stores the object as a map. This is a slow API.
You may use Google's Gson, which is an elegant and better library -- slightly more work required than JSONObject. If you are really concerned about speed, use Jackson.

Categories

Resources