Create key-value pairs string in JSON - java

I'm new to JSON. I'm trying to create a JSON string in Java (org.json.JSONObject(json.jar)) which resembles like (basically a set of name-value pairs)
[{
"name": "cases",
"value": 23
}, {
"name": "revenue",
"value": 34
}, {
"name": "1D5",
"value": 56
}, {
"name": "diag",
"value": 14
}]
Can anyone help me on how to create this in Java? I want the name and value to be in each so that i can iterate over the collection and then get individual values.

The library is chained, so you can create your object by first creating a json array, then creating the individual objects and adding them one at a time to the array, like so:
new JSONArray()
.put(new JSONObject()
.put("name", "cases")
.put("value", 23))
.put(new JSONObject()
.put("name", "revenue")
.put("value", 34))
.put(new JSONObject()
.put("name", "1D5")
.put("value", 56))
.put(new JSONObject()
.put("name", "diag")
.put("value", 14))
.toString();
Once you have the final array, call toString on it to get the output.

What you've got there is a JSON array containing 4 JSON objects. Each object contains two keys and two values. In Java a JSON "object" is generally represented by some sort of "Map".

Try to use gson if you have to work a lot with JSON in java.
Gson is a Java library that can be used to convert Java Objects into JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Here is a small example:
Gson gson = new Gson();
gson.toJson(1); ==> prints 1
gson.toJson("abcd"); ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values); ==> prints [1]

Related

How to merge two json files using google GSON in java?

this is file1.json
[
{
"name": "Leonard",
"age": 28,
"city": "Pasadena"
},
{
"name": "joey",
"age": 29,
"city": "NewYork"
}]
this is file2.json
[
{
"name": "Shelly",
"age": 28,
"city": "LA"
},
{
"name": "Chandler",
"age": 29,
"city": "NewYork"
}]
So, how to merge these 'file1.json' and 'file2.json' into a single file by using the google GSON library in java?
List.addAll() may solve the problem, partially. If the same object appears in both JSON files, you may end up with duplicated objects in the result. Say you want each object in the array to be considered "distinct" by a specific key (e.g.: "name"). Then you should take a look at jsonmerge.
I'm assuming that the output you require is a new file with a single array of objects.
Following is the code required to achieve that :
Gson gson = new Gson();
JsonReader reader1 = new JsonReader(new FileReader(new File(/path of "file1.json"/)));
List<String> data1 = gson.fromJson(reader1 , List.class);
JsonReader reader2 = new JsonReader(new FileReader(new File(/path of "file2.json"/)));
List<String> data2 = gson.fromJson(reader2, List.class);
data1.addAll(data2);
FileWriter fileWriter = new FileWriter(/path of the output file/);
gson.toJson(data1 , fileWriter);
fileWriter.flush();
fileWriter.close();
JsonReader reads a JSON encoded value as a stream of tokens. The tokens are traversed in depth-first order, the same order that they appear in the JSON document.
fromJson reads the JSON value from the reader and converts it to the type given in the second argument i.e., java.util.List
After we get the list from both the JSON files, we merge them by using addAll method of java.util.List package.
We take the merged list and use toJson to serialize the specified list into its equivalent JSON representation.
The JSON in the new file is as follows :
[{"name":"Leonard","age":28.0,"city":"Pasadena"},{"name":"joey","age":29.0,"city":"NewYork"},{"name":"Shelly","age":28.0,"city":"LA"},{"name":"Chandler","age":29.0,"city":"NewYork"}]

JSON parsing help (Native Android, java)

I am trying to do JSON parsing. The JSON data is shown below, I am trying to get the "categories". I was able to JSON parse everything else, but I am not sure what does this "categories" belong to, is it a JSONObject, JSONArray, or something else? I am a newbie and self-taught, usually I am familiar that JSONArray has form of "JSONArray": {["content"]}, and the "content" is JSONObject. But in this case, "categories":["content"]. I am trying to parse this "categories", and turn it to string. Thank you for your help.
{
"results": [
{
"type": "Restaurant",
"id": "jfhuiewjkfkdljiahueijkfnlsdiejkl1484391hjk8421k",
"score": 99.9844207764,
"dist": 15.581982823437135,
"info": "search:ta:840369014527642-US",
"poi": {
"name": "RoofTop Bar",
"categorySet": [
{
"id": 184729472943
}
],
"categories": [
"pub food",
"restaurant"
]}
}]
}
This is what I have tried:
groups = new JSONArray();
groups = response.getJSONArray("results");
if (groups.length() > 0) {
JSONObject resultObject = groups.getJSONObject(0);
if (resultObject.has("poi")) {
if (resultObject.getJSONObject("poi").has("name")) {
nameResult = resultObject.getJSONObject("poi").getString("name");
} else {
nameResult = "Information is not available.";
}
if (resultObject.getJSONObject("poi").has("categories")) {
JSONObject categoriesResult;
categoriesResult = resultObject.getJSONObject("categories").toString();
}
results is an array of objects
The first object contains a property called poi
poi contains a property called categories
So using the top to bottom approach, we can arrive at
const categoriesArray = results[0].poi.categories; // gives categories as an array of strings
const categoriesString = categoriesArray.join(",") // gives categories as string, with comma separated values
I am not sure if it is the actual raw data but the poi object where the categories are contained is malformed. It is missing a closing bracket which could be causing parsing issues.
That apart, the field categories from the poi object is a list of strings I am not sure how you want to format it to a string but you could loop through them and do want you want with them.
In order to obtain them you can access them from your object with results[0].poi.categories or loop through the results before accessing the categories with result.poi.categories where result is the variable containing the currently looped result.
EDIT:
From your code sample, assuming response is a JSONObject you can do the following.
Then to obtain categories in a string without the array format, you can loop through the categories and concatenate them to a string.
String categories = resultObject.get("categories").join(", ");

Searching JSon string using java

I am new To JSon and i want to search the following json string and get the required output.
String:
{"status":"Success","code":"200","message":"Retrieved Successfully","reason":null,"
"projects":
[
{
"projectName": "example",
"users":
[
{
"userName": "xyz",
"executions":
[
{
"status": "check",
"runs":
[
{
"Id": "------",
"Key": "---"
}
],
"RCount": 1
}
],
"RCount": 1
}
],
"RCount": 1
},
Like that i have many projects and now , if i give projectname and username as input i wantt to get its status as output.
Is it possible?If yes how?
You may use JSONObject for this.
JSONObject json = new JSONObject(string);
JSONArray[] projectsArray = json.getJSONArray("projects");
for(int i = 0; i < projectsArray.length; ++i)
{
String projectName = projectsArray[i].getString("projectName");
...
}
Use the same method to get the users.
You can use gson library. Using gson convert your json string to Map and then you can iterate through map to get required item
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> myMap = gson.fromJson(jsonString, type);
You can use the Google gson to map your json data structure to a Java POJOs.
Example :
You can have Projects class containing list/array of Users.
Users class containing list/array of Executions and so on.
Gson library can easily map the json to these classes as objects and you can access your data in a more elegant manner.
Here are a few references :
http://howtodoinjava.com/2014/06/17/google-gson-tutorial-convert-java-object-to-from-json/
http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

JSON deserialization with Gson

This is my JSON data:
{
"boards": [
{
"board": "3",
"title": "3DCG",
"ws_board": 1,
"per_page": 15,
"pages": 11
},
{
"board": "a",
"title": "Anime & Manga",
"ws_board": 1,
"per_page": 15,
"pages": 11
},
{
"board": "adv",
"title": "Advice",
"ws_board": 1,
"per_page": 15,
"pages": 11
},
...
]
}
This is my code for deserialization:
JSONObject json = readJsonFromUrl("http://api.4chan.org/boards.json");
String jsonBoards = json.toString();
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(jsonBoards, map.getClass());
But it doesn't get the job done. I need a way to get the boards name, title, and all the that information for each board. When I use map.get(); the key is "boards" but I want a map of every board and title and so on.
You need a class structure that maps your JSON data. You don't need to use a Map anywhere, since your JSON does not represent any map!
In fact it represents an object {...} that contains a field called "boards", which in turn represents an array [...] of objects {...}...
So the class structure that matches your JSON would be something like this (in pseudo-code):
class Response
List<Board> boards
class Board
String board
String title
int ws_board
int per_page
int pages
Then, in order to parse the JSON into your class structure, you just need to do this:
Gson gson = new Gson();
Response response = gson.fromJson(jsonBoards, Response.class);
So you'll have all the data of all your boards into:
String nameI = response.getBoards().get(i).getName();
String titleI = response.getBoards().get(i).getTitle();
//and so on...

Parse json string for specific value using JSONObject

In java, I am trying to parse values from this json..
[
{
"2012-01-02": {
"age": 3,
"dob": "2010-01-03",
"name": "jack"
},
"2012-01-03": {
"age": 3,
"dob": "2010-01-04",
"name": "jill"
},
"2012-01-04": {
"age": 3,
"dob": "2010-01-05",
"name": "john"
},
"2012-01-05": {
"age": 3,
"dob": "2010-01-06",
"name": "miran"
}
}
]
Using JSONObject, I was trying to get the value of just "age" and then add them up to do some data manipulation.
I created a JSONObject
Created an iterator and then stored them to a map
This gets me the inner element like:
{
"age": 3,
"dob": "2010-01-06",
"name": "miran"
}
After this, not sure how to extract just age from each element. Do i create another jsonobject and pass this new string, extract age out of it or is there a better way to do this? (I am sure there is one)
UPDATE:
This is what I currently have that gives me {"age":3,"dob":"2012-01-06","name":"miran"}
JSONObject jsonobj = new JSONObject();
try {
jsonobj = new JSONObject(pastweekVol);
Iterator iter = jsonobj.keys();
Map<String, String> map = new HashMap<String, String>();
while(iter.hasNext()){
String jsonkey = (String)iter.next();
String value = jsonobj.getString(jsonkey);
logger.debug("first pass value is: {}", value);
} catch (JSONException je) {
logger.debug("exception is: {}",je);
}
I was thinking that since I am getting {"age":3,"dob":"2012-01-06","name":"miran"}, I would create another json object and pass in this string, which will give me value of "age". The problem here is that I get repetitive values. Of course, something very basic is missing here but I can't seem to figure that out.
If you have the inner element as a JSONObject instance - say person - then you can directly access the age:
int age = person.getInt("age");
and do something with it:
sum += age;
You might consider a library like Google's GSON (http://code.google.com/p/google-gson/) if you want to be able to easily parse arbitrarily complex JSON strnigs into generic objects.
Using org.json is probably not your best bet -- this API has many flaws. Using Jackson, you can easily extract age from each member value:
ObjectMapper mapper = new ObjectMapper();
JsonNode fullDocument = mapper.readTree(xxx); // xxx can be many things
// Not an object? Bail out
if (!fullDocument.isObject())
throw new IllegalArgumentException("not an object");
// This will iterate through object values
for (JsonNode value: fullDocument)
// do something with value.get("age")
// in particular, you can test for .isIntegralNumber()

Categories

Resources