I am working on getting hashtags list from tweets collection , I gathered tweets into file and then append to a string through bufferReader.
If I write JSONObject obj=new JSONObject(String name) ,then I am able to read only Object1 JSON data. After this point I got stuck and not sure how do I get second ,third and so on iteratively. Is there any programming way to find array of JSON objects from the string(which has JSON data) or any other way?
When concatenating the JSON Object Representations, would need to start with JSON Array representation and each of the JSON Object Representation should be separated by comma.
public class JSonTest {
public static void main(String[] args) {
String json1 = "{ \"id\": 1, \"name\": \"A green door\", \"price\": 12.50, \"tags\": [\"home\", \"green\"]}";
String json2 = "{ \"id\": 2, \"name\": \"A blue door\", \"price\": 1.50, \"tags\": [\"home\", \"blue\"]}";
// Printing concatenated JSON Representation
JSONObject jsonObject = new JSONObject(json1 + json2); // Will see only
// first object
System.out.println(jsonObject);
// Printing Array representation
JSONArray array = new JSONArray("[" + json1 + "," + json2 + "]");
System.out.println(array);
}
}
Output:
{"tags":["home","green"],"id":1,"price":12.5,"name":"A green door"}
[{"tags":["home","green"],"id":1,"price":12.5,"name":"A green door"},{"tags":["home","blue"],"id":2,"price":1.5,"name":"A blue door"}]
Related
I am using json library to convert json to xml but while converting I want to ignore a nested json object to be converted to xml tags.
eg.
Plane json is as :
{"id":"9568","name":"Customer Analysis","group":"demo","param":{"globalSettings":{"showLegends":false,"legendPosition":"bottom center"}}}
JSONObject json = new JSONObject("{\"id\":\"9568\",\"name\":\"Customer Analysis\",\"group\":\"demo\",\"param\":{\"globalSettings\":{\"showLegends\":false,\"legendPosition\":\"bottom center\"}}}");
String xml = XML.toString(json);
System.out.println(xml);
Now in above example, I want in xml with a json as it is inside. Whereas now various elements are created for showLegends and legendPosition inside globalSettings.
Current XML is as follows :
<name>Customer Analysis</name>
<id>9568</id>
<group>demo</group>
<param>
<globalSettings>
<showLegends>false</showLegends>
<legendPosition>bottom center</legendPosition>
</globalSettings>
</param>
Expected XML should be as follows :
<name>Customer Analysis</name>
<id>9568</id>
<group>demo</group>
<param>
<globalSettings>
{"showLegends":false,"legendPosition":"bottom center"}
</globalSettings>
</param>
How can I handle this?
I think you need to tweak JSON before converting.
Can you try this below?
String json = "{\n" +
" \"user\": \"gerry\",\n" +
" \"likes\": [1, 2, 4],\n" +
" \"followers\": {\n" +
" \"options\": {\n" +
" \"key1\": \"a\",\n" +
" \"key2\": \"b\"\n" +
" } \n" +
" }\n" +
"}";
JSONObject jsonObject = new JSONObject(json);
JSONObject followers = jsonObject.getJSONObject("followers");
String options = followers.optString("options");
followers.put("options", options);
String s = XML.toString(jsonObject);
System.out.println(XML.unescape(s));
result:
<followers><options>{"key1":"a","key2":"b"}</options></followers><user>gerry</user><likes>[1,2,4]</likes>
Extra Question:
What if I don't want options as an xml element and it should be part of json?
String json = "{\n" +
" \"user\": \"gerry\",\n" +
" \"likes\": [1, 2, 4],\n" +
" \"followers\": {\n" +
" \"options\": {\n" +
" \"key1\": \"a\",\n" +
" \"key2\": \"b\"\n" +
" } \n" +
" }\n" +
"}";
JSONObject jsonObject = new JSONObject(json);
jsonObject.put("followers", jsonObject.optString("followers"));
// org.json 20180813
String s = XML.toString(jsonObject);
System.out.println(XML.unescape(s));
result:
<followers>{"options":{"key1":"a","key2":"b"}}</followers><user>gerry</user><likes>1</likes><likes>2</likes><likes>4</likes>
You need to modify your json a bit:
String json = "{\"user\":\"gerry\",\"likes\":[1,2,4],\"followers\":{\"options\":\"{key1:a,key2:b}\"}}";
JSONObject jsonObject = new JSONObject(json);
String xml = XML.toString(jsonObject);
System.out.println(XML.unescape(xml));
note that the "options" should be as "String" (shaped like JSON), then the XML parser will treat it as a regular string.
You either need to tweak the JSON before conversion, or tweak the XML after conversion.
Since such tweaking is so often required, one approach is to do the conversion using XSLT 3.0 so you have transformation capability built-in to the tool.
Underscore-java library has static methods U.fromJson(json) and U.toXml(map). You may modify map and generate xml. I am the maintainer of the project.
Map<String, Object> map = U.fromJsonMap("{\"id\":\"9568\",\"name\":\"Customer Analysis\",\"group\":\"demo\",\"param\":{\"globalSettings\":{\"showLegends\":false,\"legendPosition\":\"bottom center\"}}}");
U.set(map, "param.globalSettings", U.toJson((Map<String, Object>) U.get(map, "param.globalSettings")));
System.out.println(U.toXml(map));
Output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<id>9568</id>
<name>Customer Analysis</name>
<group>demo</group>
<param>
<globalSettings>{
"showLegends": false,
"legendPosition": "bottom center"
}</globalSettings>
</param>
</root>
I have a below JSON Array and I am trying to parse it but it is giving me an exception:
[{
"response": {
"client": "123456",
"111": {
"data": "0\u00181535480381\u00191535480347\u0018\"voyager\";-1;12;0\u00181535480075\u00191535480069",
"time": "981542121421"
}
}
}]
I am using org.json.JSONArray to parse the above JSON but below code throws exception:
String json =
"[{ \"response\": { \"client\": \"123456\", \"111\": { \"data\": \"0\u00181535480381\u00191535480347\u0018\"voyager\";-1;12;0\u00181535480075\u00191535480069\", \"time\": \"981542121421\" } } }]";
// this line throws exception
JSONArray jsonArray = new JSONArray(json);
Here is the exception I am seeing:
Exception in thread "main" org.json.JSONException: Expected a ',' or '}' at character 81
at org.json.JSONTokener.syntaxError(JSONTokener.java:410)
at org.json.JSONObject.<init>(JSONObject.java:222)
at org.json.JSONTokener.nextValue(JSONTokener.java:344)
at org.json.JSONObject.<init>(JSONObject.java:205)
at org.json.JSONTokener.nextValue(JSONTokener.java:344)
at org.json.JSONObject.<init>(JSONObject.java:205)
at org.json.JSONTokener.nextValue(JSONTokener.java:344)
at org.json.JSONArray.<init>(JSONArray.java:125)
at org.json.JSONArray.<init>(JSONArray.java:157)
What is wrong I am doing here?
Put esacpe charaters around voyager like below.
\\\"voyager\\\"
I tested it worked.
import org.json.JSONArray;
public class Test {
public static void main(String[] args) {
String json = "[{ \"response\": { \"client\": \"123456\", \"111\": { \"data\": \"0\u00181535480381\u00191535480347\u0018\\\"voyager\\\";-1;12;0\u00181535480075\u00191535480069\", \"time\": \"981542121421\" } } }]";
// this line throws exception
JSONArray jsonArray = new JSONArray(json);
}
}
Since it has already escape characters in JOSN you need to double escape in java to retain them.
\"voyager\"
This needs to be double escaped. The parser is seeing the \" as the end of the quote and expecting , or }
Try
\\\"voyager\\\"
In JSON syntax, you were wrong one place - "111", because names must be strings. thus, #NarayanP's code would not run on android system.
Your code throws exception, this is not json's mistake. problems are in assignment line;
String json = "...";
if you put below value into json through http response or file reading
"data": "0\u00181535480381\u00191535480347\u0018\"voyager\";-1;12;0\u00181535480075\u00191535480069"
then actually json's value will be
data: 015354803811535480347"voyager";-1;12;015354800751535480069 [escaped \u0018 etc. by stackoverflow]
if the JSON string contains a semicolon then only the part of the string up until the first semicolon encountered was being returned.
thus, while parsing upper json string, data item will be same as
015354803811535480347"voyager"
Then "-1","12" are JSON syntax errors.
Following is full-code without errors.
String json = "[{\n" +
" \"response\": {\n" +
" \"client\": \"123456\",\n" +
" \"varname111\": {\n" +
" \"data\": \"0\\u00181535480381\\u00191535480347\\u0018\\\"voyager\\\";-1;12;0\\u00181535480075\\u00191535480069\",\n" +
" \"time\": \"981542121421\"\n" +
" }\n" +
" }\n" +
"}]";
JSONArray jsonArray = null;
try {
jsonArray= new JSONArray(json);
} catch (Exception e) {
e.printStackTrace();
}
I've been spending the last couple of days trying to format a JSON string into a JSON object, but this is not quite the usual json string. Im receiving it from an url and have no problem converting it into a string but when im going to create the JSON object Ive found a whole lot of issues.
The JSON looks like this:
header {
gtfs_realtime_version: "1.0"
incrementality: FULL_DATASET
timestamp: 1511789066
}
entity {
id: "294-131-39-562-4732025"
vehicle {
trip {
trip_id: "131-39-562-4732025"
route_id: "131"
}
position {
latitude: 3.44351
longitude: -76.52622
}
timestamp: 1511789065
stop_id: "501450"
vehicle {
id: "21002"
label: "MC21002"
license_plate: "VCQ452"
}
}
}
entity {
id: "1087-431-55-35-4732025"
vehicle {
trip {
trip_id: "431-55-35-4732025"
route_id: "431"
}
position {
latitude: 3.3767517
longitude: -76.54276
}
timestamp: 1511789065
stop_id: "502150"
vehicle {
id: "31038"
label: "MC31038"
}
}
}
as you can see there is no array, nor commas separating the element that I need to process (entity), I cant even get the JSONObject from the root.
Any suggestions?
This is the last block of code I've tried in which I remove the header, insert all the entity objects into the array buses, and separate them by commas, but is no use
//getRespuesta(); gives me the string
//Log.d("LIVE", "RAW JSon: " + getRespuesta());
String[] parts = getRespuesta().split("[}]", 2);
String[] splitter = parts[1].split("(?=entity)");
String finalString = splitter[1];
for (int t = 2; t < splitter.length; t++) {
finalString = finalString + ",\n" + splitter[t];
}
Log.d("LIVEL", "SIZE: " + splitter[1]);
String JSonChunk = "{ \n \"buses\": [ \n " + finalString + "\n ] \n }";
//String JSonChunk = "{ \n " + parts[1] + "\n }";
try {
// Log.d("LIVE", "CHUNKED JSon: " + JSonChunk);
JSONObject json = new JSONObject(JSonChunk);
}catch........
As was mentioned in the comments and as you've seen you can't use a JSON parser on non-JSON. I'd take the following approach:
If this meets the specifications of a known format, someone has probably written a JSON converter you can run it through.
If it is a custom format but each line is a predictable format and does not rely on anything before or after, you can run each line through a custom converter and give it the 'JSON-ness.' (add commas, etc) Process each line at at time rather than trying to split up the whole thing at once.
If none of the above are true, you need to go into regular expression hell. Sorry :(
From my point of view you must transform it to a valid JSON String
You can try this regex:
https://regex101.com/r/15dHwd/1
That means, for each group that capture tou replace it with ": {"
That way: "position {" will re replaced with "position: {"
Now you have other issue,
"entity" appears twice
If you are 100% sure that you will get always that format, after the first replace:
Start with appending "{" on the beginning of the string
Get a regex to find the "entity" String
Replace the first match with "array: [ entity"
List item
On the end of the string append: "]}"
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
This is my Json String and I am trying to fetch the value of Entity.I am a beginner in using JSON.
[
{
"_id": "john",
"preferences": [
{
"Entity": [
"IBM",
"Pfizer"
]
},
{
"Topic": "Pharma"
}
]
}
]
Can anyone help me on this?
try as follow :
JSONObject myjson = new JSONObject(the_json_string);
JSONArray the_json_array = myjson.getJSONArray("profiles");
for more : How to parse a JSON and turn its values into an Array?
import org.json.*;
JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
}
May be it may helps you: Parse JSON in Java
You can use gson library. If your input is a JSON string, you first need to parse it using a JsonParser object which returns us a JsonElement which is converted into JsonArray as the input Json is an array. You then extract the first object from it using get(0) and then convert it into a JsonObject, extract preferences element as JsonArray and follow similar procedure to get Entity.
String jsonString = "[" +
" {" +
" \"_id\": john," +
" \"preferences\": [" +
" {" +
" \"Entity\": [" +
" IBM," +
" Pfizer" +
" ]" +
" }," +
" {" +
" \"Topic\": Pharma" +
" }" +
" ]" +
" }" +
"]";
JsonArray jsonArray = new JsonParser().parse(jsonString).getAsJsonArray();
JsonArray preferences = jsonArray.get(0).getAsJsonObject().get("preferences").getAsJsonArray();
JsonArray entity = preferences.get(0).getAsJsonObject().get("Entity").getAsJsonArray();
I have seen many examples, but none of them are not like what i want.
Consider I have a JSONObject like:
[ {
"id" : "572add95e4b0b04f4d502a3c",
"amount" : 109.27,
"sourceCurrency" : "MXN",
"targetCurrency" : "USD",
"recipientBankId" : "572add95e4b0b04f4d502a37",
"iban" : "5805742027",
"created" : "2016-05-05T05:43:49.194"
}, {
"id" : "572add95e4b0b04f4d502a3e",
"amount" : 722.41,
"sourceCurrency" : "GBP",
"targetCurrency" : "INR",
"recipientBankId" : "572add95e4b0b04f4d502a32",
"iban" : "4688276585",
"created" : "2016-05-05T05:43:49.2"
}]
and i want to access to the second json and iban value.
How can i do it?
With your json content
String json = "[ {\n" +
" \"id\" : \"572add95e4b0b04f4d502a3c\",\n" +
" \"amount\" : 109.27,\n" +
" \"sourceCurrency\" : \"MXN\",\n" +
" \"targetCurrency\" : \"USD\",\n" +
" \"recipientBankId\" : \"572add95e4b0b04f4d502a37\",\n" +
" \"iban\" : \"5805742027\",\n" +
" \"created\" : \"2016-05-05T05:43:49.194\"\n" +
"}, {\n" +
" \"id\" : \"572add95e4b0b04f4d502a3e\",\n" +
" \"amount\" : 722.41,\n" +
" \"sourceCurrency\" : \"GBP\",\n" +
" \"targetCurrency\" : \"INR\",\n" +
" \"recipientBankId\" : \"572add95e4b0b04f4d502a32\",\n" +
" \"iban\" : \"4688276585\",\n" +
" \"created\" : \"2016-05-05T05:43:49.2\"\n" +
"}]";
You first need to get a JSONArray from your json content :
JSONArray array = new JSONArray(json);
Then you read the second ( at the index 1 ) JSONObject within the array:
JSONObject o = array.getJSONObject(1);
And finally you read the iban from the JSONObject :
String secondIban = o.getString("iban");
System.out.println(secondIban);
With of course all this surrounded with a try/catch to catch JSONException:
try {
JSONArray array = new JSONArray(json);
JSONObject o = array.getJSONObject(1);
String secondIban = o.getString("iban");
System.out.println(secondIban);
}catch(JSONException jse){
jse.printStackTrace();
}
Note
If you want to be aware that the iban field doesn't exist use o.getString("iban").
A JSONException will be thrown if the field is missing.
If you are okay to work with an empty string "" as default value for the eventually missing field then use o.optString("iban") to read the field.
you can do something like below.
public static void main(String[] args) {
String json = "[{\n" +
" \"id\" : \"572add95e4b0b04f4d502a3c\",\n" +
" \"amount\" : 109.27,\n" +
" \"sourceCurrency\" : \"MXN\",\n" +
" \"targetCurrency\" : \"USD\",\n" +
" \"recipientBankId\" : \"572add95e4b0b04f4d502a37\",\n" +
" \"iban\" : \"5805742027\",\n" +
" \"created\" : \"2016-05-05T05:43:49.194\"\n" +
"}, {\n" +
" \"id\" : \"572add95e4b0b04f4d502a3e\",\n" +
" \"amount\" : 722.41,\n" +
" \"sourceCurrency\" : \"GBP\",\n" +
" \"targetCurrency\" : \"INR\",\n" +
" \"recipientBankId\" : \"572add95e4b0b04f4d502a32\",\n" +
" \"iban\" : \"4688276585\",\n" +
" \"created\" : \"2016-05-05T05:43:49.2\"\n" +
"}]";
JSONArray objects = new JSONArray(json);
System.out.println(((JSONObject)objects.get(1)).get("iban"));
}
Use optString instead getString.
optString - Will return blank string if element/key not found in JSON.
getString - Will throw an exception.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
================================
public static void main(String[] args) throws JSONException {
String str = "[{\"id\":\"572add95e4b0b04f4d502a3c\",\"amount\":109.27,\"sourceCurrency\":\"MXN\",\"targetCurrency\":\"USD\",\"recipientBankId\":\"572add95e4b0b04f4d502a37\",\"iban\":\"5805742027\",\"created\":\"2016-05-05T05:43:49.194\"},{\"id\":\"572add95e4b0b04f4d502a3e\",\"amount\":722.41,\"sourceCurrency\":\"GBP\",\"targetCurrency\":\"INR\",\"recipientBankId\":\"572add95e4b0b04f4d502a32\",\"iban\":\"4688276585\",\"created\":\"2016-05-05T05:43:49.2\"}]";
JSONArray jsonArray = new JSONArray(str);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
/* optString - will return blank string if element not found */
String iban = jsonObject.optString("iban");
System.out.println(iban);
}
}
What you should do is transform string into json:
public JsonObject parseJsonString(String jsonString) {
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString);
return jsonObject;
}
then extract values that you are after:
final String iban = jsonObject.get("iban").getAsString();
To read a value from JSON you can only with the next methods:
Data bind
Tree Model
Streaming API
XPath like
Which method to use is up to you because all methods have advantage and disadvantage.
Engines:
Fastjson supports Data bind, XPath like
Gson supports Data bind, Tree Model, Streaming API
Jackson supports Data bind, Tree Model, Streaming API
JsonPath supports XPath like
Genson supports Data bind, Tree model with Jsonp, Streaming API
Ig json parser supports Data bind
Moshi supports Data bind
JSON java supports Tree Model
LoganSquare supports Data bind
I guess you want to select only a part from json, so xpath like could be your choice with syntax like this $[1].iban (JsonPath)