[{"name":"RAJGOWTHAMAN R","branch":"B.Tech - Information Technology","details":[{"semester":"6","subcode":"10 IT 611","subname":"Object Oriented Analysis and Design","grade":"C","result":"Pass"},{"semester":"6","subcode":"10 IT 612","subname":"Visual Programming","grade":"C","result":"Pass"},{"semester":"6","subcode":"10 IT 613","subname":"Web Technology","grade":"E","result":"Pass"},{"semester":"6","subcode":"10 IT 614","subname":"Cryptography and Network Security","grade":"E","result":"Pass"},{"semester":"6","subcode":"10 IT 615","subname":"System Software","grade":"D","result":"Pass"},{"semester":"6","subcode":"10 IT 6P1","subname":"Visual Programming Laboratory","grade":"A","result":"Pass"},{"semester":"6","subcode":"10 IT 6P2","subname":"CASE Tools Laboratory","grade":"C","result":"Pass"},{"semester":"6","subcode":"10 IT 6P3","subname":"Web Technology Laboratory","grade":"S","result":"Pass"},{"semester":"6","subcode":"10 IT E13","subname":"Software Quality Management","grade":"RA","result":"Fail"}]}]
how can I parse the above json
There are a number of JSON libraries available in Java:
gson
json-simple
Here's code snippet to parse the JSON string using json-simple:
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
...
String jsonLine = "[{ ... }]";
// first have to parse JSON into object
Object obj = JSONValue.parse(jsonLine);
JSONArray array = (JSONArray)obj;
JSONObject value = (JSONObject)array.get(0);
// JSONObject extends HashMap so can access properties as any Map
System.out.println("keys=" + value.keySet());
JSONArray details = (JSONArray) value.get("details");
// do something with details object
From your example, this would output:
keys=[name, details, branch]
json-simple has many examples to decode JSON:
https://github.com/fangyidong/json-simple/wiki
Using gson the code is nearly identical:
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonElement value = jelement.getAsJsonArray().get(0);
JsonArray details = value.getAsJsonObject().get("details").getAsJsonArray();
Related
I am currently using the Json-simple jar file and need to convert my json object into json array, I read on many places to use:
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject) parse.parse(jsonString);
JSONArray arr = jsonObject.getJSONArray("users");
However the getJSONArray() method isn't being recognized. It says cannot find symbol. I have imported all of the org.json package but not sure how this works.
My JSON is coming from a url and is:
{
"warnings":[
],
"users":[
{
"id":12345678,
"username":"abc123",
"firstname":"ABC",
"lastname":"DEF",
"fullname":"ABC",
"email":"abc#gmail.com",
"department":"Autoz",
"idnumber":"1234",
"firstaccess":2552,
"lastaccess":4242,
"auth":"ldap",
"suspended":false,
"confirmed":true,
"lang":"en",
"theme":"",
"timezone":"99",
"mailformat":1,
"description":"Software Engineer",
"descriptionformat":1,
"city":"Lahore",
"profileimageurlsmall":"srwegwegdrz",
"profileimageurl":"rbdrrebhez"
}
]
}
Now, I try to link that fullcalendar in jQuery UI and Database(Oracle 10g). But, a problem has occurred.
I want to parse that JsonArray from String of JsonArray format.
ex)
String of JsonArray format
-> String jsonArrayStr="[{test1:'test',test2:2,test3:'test3'},
{test1:'test',test2:2,test3:'test3'},
{test1:'test',test2:2,test3:'test3'}]";
String of JsonArray format->JsonArray
->JSONArray jsonArray = **(?)**
How you can convert JsonArray from String of JsonArray format in Java?
like this using this library
String jsonArrayStr="[{test1:'test',test2:2,test3:'test3'},{test1:'test',test2:2,test3:'test3'}, {test1:'test',test2:2,test3:'test3'}]";
JSONArray jrr = new JSONArray(jsonArrayStr);
You are confusing me with your tags: "java" and "jquery", did you mean "JavaScript"? Because Java has no relation with jQuery....
If you mean JavaScript, this may be your solution:
var jsonArrayStr = "[{test1:'test',test2:2,test3:'test3'},{test1:'test',test2:2,test3:'test3'}, {test1:'test',test2:2,test3:'test3'}]";
var jsonArray = JSON.parse( jsonArrayStr );
If you mean really Java, try the following code:
JSONArray jsonArray = new JSONArray(jsonArrayStr);
Dependencies:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
I have JSON string which is in a standalone Java project:
{"MsgType":"AB","TID":"1","ItemID":"34532136","TransactTime":1389260033223}
I want to extract MsgType from this which is AB
Which is the best way to do it?
You can use Gson library for this.
String json="{MsgType:AB,TID:1,ItemID:34532136,TransactTime:1389260033223}";
Map jsonJavaRootObject = new Gson().fromJson(json, Map.class);
System.out.println(jsonJavaRootObject.get("MsgType"));
where the jsonJavaRootObject will contain a map of keyvalues like this
{MsgType=AB, TID=1.0, ItemID=3.4532136E7, TransactTime=1.389260033223E12}
I use JSONObject under android but from Oracle docs I see its also available under javax.json package:
http://docs.oracle.com/javaee/7/api/javax/json/package-summary.html
If you want Gson then your code should look like below (sorry not compiled/tested):
/*
{"MsgType":"AB","TID":"1","ItemID":"34532136","TransactTime":1389260033223}
*/
Gson gson = new Gson();
static class Data{
String MsgType;
String TID;
String ItemID;
int TransactTime;
}
Data data = gson.fromJson(yourJsonString, Data.class);
I have an example with json-simple:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(yourString);
String msgType = (String) jsonObject.get("MsgType");
Check this link for a complete example.
JsonPath
For parsing simple JSON use JsonPath
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document.
Example code
String json = "{\"MsgType\":\"AB\",\"TID\":\"1\",\"ItemID\":\"34532136\",\"TransactTime\":1389260033223}";
String author = JsonPath.read(json, "$.MsgType");
System.out.println(author);
Result
AB
Dependency
'com.jayway.jsonpath:json-path:0.9.1'
I am using the following library to parse an object:
{"name": "web", "services": []}
And the following code
import com.json.parsers.JSONParser;
JSONParser parser = new JSONParser();
Object obj = parser.parseJson(stringJson);
when the array services is empty, it displays the following error
#Key-Heirarchy::root/services[0]/ #Key:: Value is expected but found empty...#Position::29
if the array services has an element everything works fine
{"name": "web", "services": ["one"]}
How can I fix this?
Thanks
Try using org.json.simple.parser.JSONParser
Something like this:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(stringJson);
Now to access the fields, you can do this:
JSONObject name = jsonObject.get("name"); //gives you 'web'
And services is a JSONArray, so fetch it in JSONArray. Like this:
JSONArray services = jsonObject.get("services");
Now, you can iterate through this services JSONArray as well.
Iterator<JSONObject> iterator = services.iterator();
// iterate through json array
while (iterator.hasNext()) {
// do something. Fetch fields in services array.
}
Hope this would solve your problem.
Why do you need parser?
try this:-
String stringJson = "{\"name\": \"web\", \"services\": []}";
JSONObject obj = JSONObject.fromObject(stringJson);
System.out.println(obj);
System.out.println(obj.get("name"));
System.out.println(obj.get("services"));
JSONArray arr = obj.getJSONArray("services");
System.out.println(arr.size());
I solve the problen with https://github.com/ralfstx/minimal-json
Reading JSON
Read a JSON object or array from a Reader or a String:
JsonObject jsonObject = JsonObject.readFrom( jsonString );
JsonArray jsonArray = JsonArray.readFrom( jsonReader );
Access the contents of a JSON object:
String name = jsonObject.get( "name" ).asString();
int age = jsonObject.get( "age" ).asInt(); // asLong(), asFloat(), asDouble(), ...
Access the contents of a JSON array:
String name = jsonArray.get( 0 ).asString();
int age = jsonArray.get( 1 ).asInt(); // asLong(), asFloat(), asDouble(), ...
Using Google Gson library how can I inject a element in the root node of a JSON string?
With JSON.Simple it very easy:
String json = ...
JSONObject jsonObj = (JSONObject) JSONValue.parse(json);
jsonObj.put("hey", "yow!");
json = jsonObj.toJSONString(); // Now we have injected a node element
I've been figuring out how can do this with Gson. You might ask why I need Gson when I can do this with JSON.Simple library; the answer is that, there's a handy object serialization/deserialization function that the library have.
The code is strikingly similar:
String json = ...;
JsonObject jsonObj = (JsonObject) new JsonParser().parse(json);
jsonObj.addProperty("hey", "yow!");
json = jsonObj.toString();