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.
Related
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.
For a java data handler, I send properly formatted JSON, but a combination of Spring, Java deciding how to cast what it sees, and frameworks I really shouldn't go changing mangle that JSON so that once I can see it, it's turned into a LinkedTreeMap, and I need to transform it into a JsonObject.
This is not to serialize/de-serialize JSON into java objects, it's "final form" is a gson JsonObject, and it needs to be able to handle literally any valid JSON.
{
"key":"value",
"object": {
"array":[
"value1",
"please work"
]
}
}
is the sample I've been using, once I see it, it's a LinkedTreeMap that .toString() s to
{key=value, object={array=[value1, please work]}}
where you can replace "=" with ":", but that doesn't have the internal quotes for the
new JsonParser().parse(gson.toJson(STRING)).getAsJsonObject()
strategy.
Is there a more direct way to convert LinkedTreeMap to JsonObject, or a library to add the internal quotes to the string, or even a way to turn a sting into a JsonObject that doesn't need the internal quotes?
You'd typically have to serialize the object to JSON, then parse that JSON back into a JsonObject. Fortunately, Gson provides a toJsonTree method that kind of skips the parsing.
LinkedTreeMap<?,?> yourMap = ...;
JsonObject jsonObject = gson.toJsonTree(yourMap).getAsJsonObject();
Note that, if you can, just deserialize the JSON directly to a JsonObject with
gson.fromJson(theJson, JsonObject.class);
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!
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");
I have a json string (the stream of social network Qaiku). How can I decode it in Java?
I've searched but any results work for me.
Thank you.
Standard way of object de-serialization is the following:
Gson gson = new Gson();
MyType obj = gson.fromJson(json, MyType.class);
For primitives corresponding class should be used instead of MyType.
You can find more details in Gson user's guide. If this way does not work for you - probably there's some error in JSON input.
As an example using Gson, you could do the following
Gson gson = new Gson();
gson.fromJson(value, type);
where value is your encoded value. The trick comes with the second parameter - the type. You need to know what your decoding and what Java type that JSON will end in.
The following example shows decoding a JSON string into a list of domain objects called Table:
http://javastorage.wordpress.com/2011/03/31/how-to-decode-json-with-google-gson-library/
In order to do that the type needs to be specified as:
Type type = new TypeToken<List<Table>>(){}.getType();
Gson is available here:
http://code.google.com/p/google-gson/