How to store json data in String variables. I tried but it is showing an error.I want to store below json in one normal string.I tried lot it's always showing error.
[
{
"order":0,
"name":"expenseType",
"required":true,
"type":"text",
"placeholder":"Expense Type"
},
{
"order":1,
"name":"date",
"required":true,
"type":"text",
"placeholder":"Expense Date"
},
{
"order":3,
"name":"amount",
"required":true,
"type":"number",
"placeholder":"Enter Amount"
},
{
"order":4,
"name":"description",
"required":true,
"type":"text",
"placeholder":"Description"
},
{
"order":5,
"name":"imageUrls",
"type":"fileUpload",
"options":[ urls:string]
}
]
Error: org.json.JSONException: Unterminated array at character 641
Just use toString() on JsonObject.
String jsonString=jsonObject.toString();
Rcreate Json Object from String .
JSONObject jsonObject=new JSONObject(jsonString);
If you want Json String as constant then just paste it beetween double quotes. Example json .
{
"token":"",
"type":"1",
"message":{
"type":1,
"message":"message"
}
}
And as String it is.
String jsonString ="{\n" +
" \"token\":\"\",\n" +
" \"type\":\"1\",\n" +
" \"message\":{\n" +
" \"type\":1,\n" +
" \"message\":\"message\"\n" +
" }\n" +
"}";
you can use GSON , create your object class
Gradle :
compile 'com.google.code.gson:gson:2.8.2'
Java :
Gson gson = new Gson();
String myJson = "my string json array";
List<Object> list= gson.fromJson(myJson,new TypeToken<List<Object>>(){}.getType());
See the Documentation
Related
I have a json string as:
string jsonString = "{"Header":{"ID": "103","DateTime": "2020-07-29 09:14:23.802-4:00 1","PlazaID": "01","Lane": "Lane 20","IPAddr": "192.9.0.123"},"Body": {"EventMsg": "Status: Online","EventNum": "99999"}}";
I am trying to get the value if ID from the above json by using Gson and it gives me NullPointerException. My code:
JsonObject jsonObject = new Gson().fromJson(jsonString, JsonObject.class );
//System.out.println("jsonObject: " + jsonObject.toString());
String _ID = jsonObject.get("ID").getAsString();
I am not sure where the error in my code is. Any help is appreciated.
Edit:
As per #Arvind's suggestion, I tried his code and am getting this error:
As per #Arvind's suggestion, this works:
String _ID = jsonObject.get("Header").getAsJsonObject().get("ID").getAsString();
Let's prettify your jsonString first for clarity:
{
"Header": {
"ID": "103",
"DateTime": "2020-07-29 09:14:23.802-4:00 1",
"PlazaID": "01",
"Lane": "Lane 20",
"IPAddr": "192.9.0.123"
},
"Body": {
"EventMsg": "Status: Online",
"EventNum": "99999"
}
}
Notice that "ID" is inside "Header", so you'd have to parse it this way:
String _ID = jsonObject.getJsonObject("Header").get("ID").getAsString();
Also, avoid using get() since there are better convenience methods:
String _ID = jsonObject.getJsonObject("Header").getString("ID");
import org.json.JSONObject;
import org.json.XML;
public class Example {
public static void main(String[] args) {
String xmlString = "<users><user name=test1 age=20></user><type><direct num=3></direct></type><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
System.out.println(jsonObject);
}
}
I can remove elements after conversion from xml to json. But actually what i needed is that, the elements or attributes should be removed during conversion itself.
My required output is:
{
"users": {
"report": {
"score": 30
},
"type": {
"direct": {
"num": 3
}
},
"user": {
"age": 20
}
}
}
XML class does not provide methods to exclude tags. One possible solution is update the string to remove tags as below,
e.g to exclude type tag,
String splits[] = xmlString.split("(<\\/type>|<type>)");
xmlString = splits[0]+splits[2];
JSONObject jsonObject = XML.toJSONObject(xmlString);
System.out.println(jsonObject);
Output:
{"users":{"report":{"sub":"eng","score":30},"user":{"name":"test1","age":20}}}
To remove name element from user tag,
String xmlString = "<users><user name=test1 age=20></user><type><direct num=3></direct></type><report sub=eng score=30></report></users>";
//split by user tags
String splits[] = xmlString.split("(<\\/user>|<user )");
//remove name filed and combine other elements
String user1 = Arrays.stream(splits[1].split(" "))
.filter(s->!s.contains("name"))
.collect(Collectors.joining(" "));
//merge strings and user tag
xmlString = splits[0] + "<user " + user1 + "</user>" + splits[2];
JSONObject jsonObject = XML.toJSONObject(xmlString);
Output::
{
"users": {
"report": {
"sub": "eng",
"score": 30
},
"type": {
"direct": {
"num": 3
}
},
"user": {
"age": 20
}
}
}
UPDATE:
The best solution would be to remove from JsonObject,
jsonObject.getJSONObject("users").getJSONObject("user").remove("name")
org.json.XML package doesn't provide internal XML modifications. If you must use this, you have to make the necessary modifications in the json by yourself. Else you can preprocess the xml using java default xml parser, convert it to string and then convert it to json.
I know the answer for parsing the JSON of this type:
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food"}
where there is key value pair, with key being same(like 'id' here) and value differing, and we use a for loop to parse it quickly.
(For those who'd like to see how to parse above JSON, please go to this link: How to parse nested JSON object using the json library?)
However, the JSON I'm trying to parse is a different one which doesn't have a same key like 'Id' as above for every different value, but every key is a new key with a different value. Below is the example:
{
"disclaimer": "Exchange rates are ...........blah blah",
"license": "Data sourced from various .......blah blah",
"timestamp": 1446886811,
"base": "USD",
"rates": {
"AED": 3.67266,
"AFN": 65.059999,
"ALL": 127.896
.
.
All the currency values.
.
}
}
I'm not sure how to parse the above one with all different keys of currencies (currency like AED and their value) and pop them up in a drop down list.
Do I have to write a new line of code for each different currency and value pair or it is in some way possible to use a for loop for this one as well.
Can someone provide some lines code if possible?
you can use org.json for this thing.
E.g.:
JSONObject json = new JSONObject("<jsonString>");
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
System.out.println("Key :" + key + " Value :" + json.get(key));
}
You could use GSON in this case. I will just print the currencies with the according rate but you can build a different data structure(a map for example) and use it in your system.
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
String jsonString = "{\n" +
" \"disclaimer\": \"Exchange rates are ...........blah blah\",\n" +
" \"license\": \"Data sourced from various .......blah blah\",\n" +
" \"timestamp\": 1446886811,\n" +
" \"base\": \"USD\",\n" +
" \"rates\": {\n" +
" \"AED\": 3.67266,\n" +
" \"AFN\": 65.059999,\n" +
" \"ALL\": 127.896\n" +
" }\n" +
"}";
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
for(Map.Entry<String, JsonElement> currency: jsonObject.getAsJsonObject("rates").entrySet()){
System.out.println("Currency "+ currency.getKey()+" has rate " + currency.getValue());
}
}
}
I have a different use case where fields in POJO itself stores JSON data, basically grouping of all data.
Now i want the complete JSON generated from above POJO.
At present i am using this method
private static Gson gson = new Gson();
public static String convertObjectToJSON(Object object) throws Exception {
String jsonResponse = gson.toJson(object);
return jsonResponse;
}
But getting output with escape characters around double quotes like below
{ \"_id\" : 234242, \"name\" : \"carlos\"}
I tried various options in GsonBuilder, but not working.
Basically, i am just grouping multiple JSON data and sending it across.
Could you please do the needful help to get rid of the escape characters around double quotes.
UPDATE:
Question is : I have 3 JSONs and need to combine them into a single JSON and need to pass it to html5 client through Spring MVC. As of now i am added the 3 JSONs into a POJO and trying to convert the same to JSON. Same is explained above.
Thanks & Regards
Venkat
I have tried below sample code and it doesn't have any escape characters around double quotes.
class MyPOJO{
private int _id;
private String name;
// getter & setter
}
String json="{ \"_id\" : 234242, \"name\" : \"carlos\"}";
MyPOJOobj=new Gson().fromJson(json, MyPOJO.class);
System.out.println(new Gson().toJson(obj));
output:
{"_id":234242,"name":"carlos"}
EDIT
If you want to combine 3 JSON string then It will be stored as List of object as illustrated below:
sample code:
String json = "[" +
" { \"_id\" : 1, \"name\" : \"A\"}," +
" { \"_id\" : 2, \"name\" : \"B\"}," +
" { \"_id\" : 3, \"name\" : \"C\"}" +
"]";
Type type = new TypeToken<ArrayList<MyPOJO>>() {}.getType();
ArrayList<MyPOJO> obj = new Gson().fromJson(json, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
output:
[
{
"_id": 1,
"name": "A"
},
{
"_id": 2,
"name": "B"
},
{
"_id": 3,
"name": "C"
}
]
Is it possible to create and parse json like this
{
"time1": { "UserId": "Action"},
"time2": { "UserId": "Action"},
"time3": { "UserId": "Action"}
}
with json-simple.jar
I would like to keep on updating the json with the element "time": { "UserId": "Action"}
Any help ? please
Yes it's possible just use this to create :
JSONObject obj=new JSONObject();
JSONObject timeObj = new JSONObject();
timeObj.put("UserId", "Action");
obj.put("time", timeObj);
and to parse
Object obj=JSONValue.parse(value);
JSONObject object=(JSONObject)obj;
JSONObject timeObj = obj.get("time");
String action = timeObj.get("UserId");
but I don't recommends you to create JSON with format like that, the JSONObject property key must be unique, I suggest you to use JSONArray instead of JSONObject
I hope this can help you
Your JSON is incorrect. You can't have duplicate time keys. Convert it into a JSON array instead.
{
"time": [
{ "UserId": "Action"},
{ "UserId": "Action"},
{ "UserId": "Action"}
]
}
Here's how you can parse this JSON string
String json =
"{\n" +
" \"time\": [\n" +
" { \"UserId\": \"Action\"},\n" +
" { \"UserId\": \"Action\"}\n" +
" ]\n" +
"}";
JSONObject jsonRoot = new JSONObject(json);
JSONArray timeArray = jsonRoot.getJSONArray("time");
System.out.println(timeArray);
// prints: [{"UserId":"Action"},{"UserId":"Action"}]
Here's how you can add a new object to this JSON array
timeArray.put(new JSONObject().put("Admin", "CreateUser"));
System.out.println(timeArray);
// prints: [{"UserId":"Action"},{"UserId":"Action"},{"Admin":"CreateUser"}]