Is there any tool to generate a String from a JSON? - java

My doubt is if there is any tool on-line or not to generate a string from a JSON. For example, I have this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
If I want to declare a String in my code with this values, so I have to write many quotation marks to have my JSON in a String acceptable format.
So I want to know if thre is some tool to generate this String?

Some good choices are:
Jackson
Gson
They have built in methods to do just whatever you need to do in an efficient way...

I can't quite tell what you want from your original question, but I assume you are trying to output a Java String that contains some JSON that you have generated.
You should use JSONObject and JSONArray to accomplish this.
To create this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
You should use this code:
JSONObject a = new JSONObject();
a.put("number", 20);
a.put("name", "androider");
JSONObject b = new JSONObject();
b.put("id", 3432);
b.put("name", "other_name");
JSONArray array = new JSONArray();
array.put(a);
array.put(b);
JSONObject root = new JSONObject();
root.put("my_json", array);
// convert the root object to a string with 4 spaces of indentation
String json = root.toString(4);

As told by Angel, Jackson and Gson are two cool libs.
Gson is very easy to use while Jackson has better performance.

Try here, Go through the answers mentioned below
How to convert String to JSONObject in Java
in short,
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
Here put your own string.
Edit:
Try here,
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
Create a Json object,
JSONObject jsonobj = new JSONObject();
Put your data using...
josnobj.put()

Related

How to import json array into java program using JSON.ORG

I am learning to work with json files and I'm using the JSON-java library from https://github.com/stleary/JSON-java
I was able to manipulate data for this json dataset
{
"timezone": "UTC",
"serverTime": 1602321831628,
"rateLimits": [
{
"rateLimitType": "REQUEST_WEIGHT",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 1200
}
],
"symbols": [
{
"symbol": "ETHBTC",
"status": "TRADING"
}
]
}
Using this code
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONObject jsonObject = new JSONObject(jsonToken);
//extract all base asset array
JSONArray symbols = jsonObject.getJSONArray("symbols");
Now I want to manipulate a dataset like this from a .json file
[
{
"symbol": "ETHBTC",
"priceChange": "-0.00029700"
},
{
"symbol": "LTCBTC",
"priceChange": "-0.00003300"
}
]
How do I import this data into my program as an array? I have looked for 8 hours, but could not find a solution. Thank you.
You are almost there, all you have to do is to new a JSON array from jsonToken as follows:
BTW, I think the JSON library you are using is org.json, not JSON.ORG. And both of your JSON strings are invalid, if no other JSON object exists behind comma, please remove it.
Code snippet
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONArray jsonArray = new JSONArray(jsonToken);
System.out.println(jsonArray.toString());
System.out.println(jsonArray.get(0));
Console output
[{"priceChange":"-0.00029700","symbol":"ETHBTC"},{"priceChange":"-0.00003300","symbol":"LTCBTC"}]
{"priceChange":"-0.00029700","symbol":"ETHBTC"}

How do you parse a nested JSON file like below using Processing JSON object?

How do you parse a nested JSON file like below using Processing JSON object? I am trying to figure out how to parse JSON that is multi-level.
{
"info": {
"description": "COCO 2014 Dataset",
"url": "http://cocodataset.org",
"version": "1.0",
"year": 2014,
"contributor": "COCO Consortium",
"date_created": "2017/09/01"
},
"images": [
{
"license": 5,
"file_name": "COCO_train2014_000000057870.jpg",
"coco_url": "http://images.cocodataset.org/train2014/COCO_train2014_000000057870.jpg",
"height": 480,
"width": 640,
"date_captured": "2013-11-14 16:28:13",
"flickr_url": "http://farm4.staticflickr.com/3153/2970773875_164f0c0b83_z.jpg",
"id": 57870
},
Have a look at JSONObject and JSONArray to see the available methods bellow on each page, each with documentation and examples.
Regarding your structure, here's a quick snippet on how you might access nested JSON objects and arrays:
// assume data is a JSONObject pointing to the loaded json data (via loadJSONObject / JSONObject.parse(), etc.
// access the info object
JSONObject info = data.getJSONObject("info");
// access the images array object
JSONArray images = data.getJSONArray("images");
// access a string inside an object
println(info.getString("description"));
// access a JSON object inside a JSON array
JSONObject firstImage = images.getJSONObject(0);
// acess an integer
println(firstImage.getInt("id"));
// ... and a string again
println(firstImage.getString("flickr_url"));
If you name your loaded JSONObject variable data, paste the the snippet above and run, it should print:
COCO 2014 Dataset
57870
http://farm4.staticflickr.com/3153/2970773875_164f0c0b83_z.jpg
You can use Gson to parse/deserialize to model class.
Or if you want to parse manually, then you have to parse a json object first and then you have to parse it again from a parsed json.
Eg.
JsonObject jsonObject = new JsonObject(jsonString);
JsonObject infoObject = jsonObject.getJsonObject("info");
String description = infoObject.getString("description");

is there an json simple function to get all the keys from a jsonobject?

I'm trying for the first time to use the jsonsimple library on java.
So i formatted a json object using a String.
the Object is the following
{
"mario":{
"city": "rome",
"birth": 1980,
"haircolor": "blonde"
},
"Lucas": {
"city": "milan",
"birth": 1985,
"haircolor": "brown"
}
}
From these object i need to get the names in a String format.
Thanks everyone for any kinda of help.
JsonObject implements java.util.Map, so you can simply call the keySet-Method on your JsonObject.
Example:
JsonObject myJsonObject = ...;
Set<String> allNamesInThisObject = myJsonObject.keySet();

json array to individual strings

Assignment: I am using json-simple. How can I convert this json data into individual java strings?
(Please forgive me if you think that this is a low-level question - I am new to JSON, so I don't know much about that - I've searched a lot, but I couldn't find any answers)
I can get the data if there is only one object ... like this ...
{
"name": "Abhi",
"age": "21"
}
But, I can't get the data if it is in the array
[{
"name": "Abhi",
"age": "21"
}, {
"name": "shek",
"age": "7"
}]
my program logic for json object
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("A:/c/dataFile.json"));
JSONObject jObj = (JSONObject) obj;
String gName = (String) jObj.get("name");
String gAge = (String) jObj.get("age");
System.out.println(gName);
System.out.println(gAge);
Can anyone show me how to get the data? maybe a code snippet?
Thanks in advance for your answer!
Because in your second case you are getting JSONArray
you may need to check the instance of obj as
if (jObj instanceof JSONObject)
else if (jObj instanceof JSONArray)

Parsing JSON Android ArrayList

I apologize if the title of my question is a bit misleading.
I created a POJO to hold CholesterolInformation about a user (HDL, LDL, Triglycerides, units, etc...). I now want to use my JSONObject to create an ArrayList so that I can generate some data points.
My JSONObject contains the following:
{
"cholesterol": [
{
"date": "2014-01-01",
"hdl": "56464.0",
"ldl": "46494.0",
"triGlycaride": "0.0",
"uid": "email#email.com",
"unit": "mg"
},
{
"date": "2014-01-01",
"hdl": "5.0",
"ldl": "5.0",
"triGlycaride": "0.0",
"uid": "email#email.com",
"unit": "mg"
},
{
"date": "2014-01-01",
"hdl": "6.0",
"ldl": "6.0",
"triGlycaride": "0.0",
"uid": "email#email.com",
"unit": "mg"
}
]
}
My question is, how would one go about iterating through this JSON Object? I would like to maybe use a for each, and create a new object to add to the ArrayList in each iteration... Do you have any advice or suggestions?
Note: I have never used the JSONObject before, and thus am not too familiar with its usage.
EDIT: Thanks everybody, that was exactly what I was looking for. I need to get more familiar with JSON manipulation. And I will look into GSON as well!
Use GSON as suggested by Eric as you already created POJO.
Gson gson = new Gson();
Type type = new TypeToken<List<POJO>>() {}.getType();
List<POJO> mList = gson.fromJson(your_json_string_here, type);
It's time to learn some JSON manipulation:
JSONArray array = yourJsonObject.optJSONArray("cholesterol");
if (array != null) {
for (int i=0; i< array.length; i++) {
JSONObject object = array.optJSONObject(i);
if (object != null) {
// this is where you manipulate all the date, hdl, ldl...etc
}
}
}
you also should check for null before accessing the json
If I understand you correctly, you want to create an ArrayList of your POJO? I assume you have getters and setters inside your POJO class. Initialize an ArrayList somewhere near the top like this
private ArrayList<CholesterolInformation> mCholesterol;
Now, parse through your json like this
JSONobject data = new JSONObject(jsonStringData);
JSONArray cholesterol = data.getJSONArray("cholesterol");
for(int i = 0; i < cholesterol.length; i++)
{
JSONObject object = cholesterol.getJSONObject(i);
// Create a new object of your POJO class
CholesterolInformation ci = new CholesterolInformation();
// Get value from JSON
String date = object.getString("date");
// Set value to your object using your setter method
ci.setDate(date);
String hdl = object.getString("hdl");
ci.setHdl(hdl);
.....
.....
// Finally, add the object to your arraylist
mCholesterol.add(ci);
}

Categories