Accessing json string using java code - java

I had following json format :
[
{ "Otype" : "win"},
{ "Otype" : "win"},
{ },
{ },
{ "Otype" : " win 7"},
{ "Otype" : " Linux"}
]
for accessing Otype I write java code as below:
while(cur.hasNext() && !isStopped()) {
String json = cur.next().toString();
JSONObject jObject = new JSONObject(json);
System.out.print(jObject.getString("Otype"));
}//end of while
So above print statement print only following results:
win
win
but not print:
{ "Otype" : " win 7"}
{ "Otype" : " Linux"}
I think it may be first white space in value field that's why it not print above two key so I changed in print statement as below:
System.out.print(jObject.getString("Otype").trim());
but still not work :( .
How I can access all above json value using java code?

I found my solution. I changed my code as below:
while(cur.hasNext() && !isStopped()) {
String json = cur.next().toString();
JSONObject jObject = new JSONObject(json);
if(jObject.has("Otype")){
System.out.print(jObject.getString("Otype"));
}//end of if
}//end of while

use toString() like this
System.out.print(jObject.toString());

Related

Get Arraylist file json using java

I have problems with my code, I need to extract the "materias" markup in the arraylist. Example data:
[{
"name": "A114",
"grupo": "DAW2",
"tutor": 15,
"materias": ["DWES", "DWEC", "IW", "DAW", "IE"]
}]
I tried this, work but i need the content of the arraylist:
try { // this read the JSON file
line = new String(Files.readAllBytes(Paths.get("fileAulas")));
} catch (Exception ex) {
ex.printStackTrace();
}
JSONArray recs = new JSONArray(line);
for (Object rec : recs) {
Aula datos = new Aula();
JSONObject obj = ((JSONObject) rec);
String name = obj.getString("name");
//datos.setNombre(name);
String grupo = obj.getString("grupo");
//datos.setGrupo(grupo);
int tutor = obj.getInt("tutor");
//datos.setTutor(tutor);
}
My objetive is to read the arraylist and then datos.setArraylist to my another class. All works fine except read the arraylist
PD: I use java downloaded from Maven, to execute i use "javac -cp ./*: program.java"
materias is also an array, so you need something like:
JSONArray materias = obj.getJsonArray("materias");
List<String> materiasList = materias.getValuesAs(String.class);
This is not type-safe so you need to make sure the array will only have String values.
Also, if you are using Java 8, you can iterate over the values and store them manually (JsonArray is also a Collection<JsonValue>)
Quickly created short test implementation of your needs:
String json = "[{ \"name\":\"A114\",\"grupo\": \"DAW2\",\"tutor\":15,\"materias\": [\"DWES\",\"DWEC\",\"IW\",\"DAW\",\"IE\"]}]";
JSONArray objectArray = new JSONArray(json);
for (int x = 0; x < objectArray.length(); x++) {
JSONObject obj = objectArray.getJSONObject(x);
System.out.println("Name: " + obj.get("name"));
System.out.println("Grupo: " + obj.get("grupo"));
System.out.println("Tutor: " + obj.get("tutor"));
JSONArray materias = obj.getJSONArray("materias");
for (int y = 0; y < materias.length(); y++) {
System.out.println("Materia " + y + ": " + materias.get(y));
}
}
Output
Name: A114
Grupo: DAW2
Tutor: 15
Materia 0: DWES
Materia 1: DWEC
Materia 2: IW
Materia 3: DAW
Materia 4: IE
First gotta make your JSON Valid.
[{
"name": "A114",
"grupo": "DAW2",
"tutor": 15,
"materias": ["DWES", "DWEC", "IW", "DAW", "IE"]
}]
Secondly, you can try the following :
for (JsonElement rec : recs) {
Aula datos = new Aula();
JSONObject obj = rec.getAsJsonObject();
String name = obj.get("name").getAsString();
//datos.setNombre(name);
String grupo = obj.get("grupo").getAsString();
//datos.setGrupo(grupo);
int tutor = obj.get("tutor").getAsInt();
JsonObject obj = rec.getAsJsonObject();
JsonArray materias = obj.getAsJsonArray("materias");
List<String> materiasList = new ArrayList<>();
for (JsonElement item:
materias) {
materiasList.add(item.getAsString());
}
}
I believe that the syntax for an array in json is different that what you have in your file. For example - a simple complete json that contains an array of simple elements would be:
{"contacts":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Jen", "lastName":"Smith" },
{ "firstName":"David", "lastName":"Jones" }
]}
In your text, you specify an array, without the opening and closing JSON '{' and '}'. Also, You would need to name the array element ("contacts" in the example above). I think that what you want would be (I used "arrayName" for the array element name):
{"arrayName":[{ "name":"A114","grupo": "DAW2","tutor":15,"materias":["DWES","DWEC","IW","DAW","IE"] },
{ "name":"121","grupo": "DAW1","tutor":8,"materias":["PROGRA","BD","SIS","LM","FOL"] },
{ "name":"A112","grupo": "AUTO1","tutor":5 },
{ "name":"A127","grupo": "ASIR1","tutor":2 },
{ "name":"A114","grupo": "SMR2","tutor":11 },
{ "name":"A128","grupo": "ASIR2","tutor":9,"materias":["IAW","ABD","ASIS","SI","IE"] },
{ "name":"A125","grupo": "ADM2","tutor":12 } ] }

JSON array from JSON object is returning null

I want to read JSON array
"connectTo":[
{
"url": "wss://localhost/opt/siml"
}
],
from JSON string :
{
"cluster":{
"enabled":"true",
"clusterName":"cluster0",
"simlURL":"wss://localhost:5443/opt/siml"
},
"simlFieldWatchUrl":"fieldwatchholder.jsp",
"persistFolder":"clusterconfig/concentratorBPersist",
"sslCrtFile":"clusterconfig/certDirB/siml.crt",
"sslKeyFile":"clusterconfig/certDirB/siml.key",
"SIMLID":"TestServerB",
"localWebProxyServer":"localhost",
"localWebProxyPort":8080,
"SIMLProxyPort":8400,
"SIMLWebPort":8300,
"turnOnExtraSIMLWebSocket":"false",
"autoPromoteNewConnectionsFromPurgatory":true,
"connectTo":[
{
"url": "wss://localhost/opt/siml"
}
],
"tempLogins":[
{
"username":"root",
"password":"root"
}
]
}
My code to read url is:
JSONArray connectTo = (JSONArray) config.get("connectTo");
System.out.println("Connect to : " + connectTo);
for (Object o : connectTo) {
JSONObject connect = (JSONObject) o;
String url = (String) connect.get("url");
System.out.println(url);
}
But System.out.println("Connect to : " + connectTo); this is returning
Connect to : []
I read some old question but did not get satisfactory answer. Please Help. And thank you in advance :)
I just assume config is a JSONObject.
JSONArray connectTo = config.getJSONArray("connectTo");
config.get() returns an Object while config.getJSONArray() returns a JSONArray.
Try this:
JSONArray connectTo =config.getJSONArray("connectTo");
System.out.println("Connect to : " + connectTo);
for (int i=0;i<connectTo.length();i++)
{
JSONObject connect = connectTo.getJSONObject(i);
String url = connect.get("url");
System.out.println(url);
}
I got it working like this, not sure if this helps:
var json = {
"connectTo": [{
"url": "wss://localhost/opt/siml"
}]
};
for (var o = 0; o < json.connectTo.length; o++) {
console.log(json.connectTo[o].url);
}

how to read JsonElement ? "This is not a JSON Array."

I have JsonElement like this:
{
"76800769": {
"prosjekLat": 45.784661646364,
"prosjekLong": 15.947804310909,
"brojCelija": 11
},
"76800772": {
"prosjekLat": 45.7847808175,
"prosjekLong": 15.9477082775,
"brojCelija": 4
},
"2946694": {
"prosjekLat": 45.78475167,
"prosjekLong": 15.9475975,
"brojCelija": 1
},
"76829440": {
"prosjekLat": 45.784726386,
"prosjekLong": 15.947961766,
"brojCelija": 5
}
}
I also create Model:
public class AddMarker {
int cellId;
double longitude;
double latitude;
}
I want to read JSON file and put values to List<AddMarker>.
I'm trying with this:
JsonElement data = response.body();
JsonObject obj = data.getAsJsonObject();
JsonArray arr = obj.getAsJsonArray();
but I'm getting an err: "This is not a JSON Array."
Your JSON is not an array.
Json Array syntax dictates that in order to have an array, your object must be formatted as:
[
{
...
},
{
...
},
...
{
...
}
]
Right now you have the outer square brackets ([]) as curly braces ({}). Change it to square brackets and your code should run correctly.
You're trying to make a array from a single object: JsonArray arr = obj.getAsJsonArray(), where obj is for exemple just this :
"76829440": {
"prosjekLat": 45.784726386,
"prosjekLong": 15.947961766,
"brojCelija": 5
}
you need to get the body from the response and make an array with all these objects, not from a single one
You can use this:
JsonObject json = new JsonObject(data);
String str1 = json.getString("76800769");
JsonObject json2 = new JsonObject(str1);
float str11 = json2.getFloat("prosjekLat");
Using org.json liberary, you can read the element as follows:
JSONObject obj = new JSONObject("your json element");
JSONObject obj2 = (JSONObject) obj.get("76800769");
System.out.println(obj2.get("brojCelija"));
System.out.println(obj2.get("prosjekLat"));
System.out.println(obj2.get("prosjekLong"));
which gives below output:
11
45.784661646364
15.947804310909
I need to convert JSON Object to array. In php just use array_values( $json ).
I solve my problem using this:
json_encode(array_values($izracunatProsjek), true);

How to parse a JSON string using ggson to get field values

I have a sample JSON as below. I need to get the individual fields like ASIdentifer and ExternalIdentifer. I have stored this JSON data in a string.
Using GoogleJson as the module(ggson)
JSON data:
{
"DeviceCommon": {
"ASIdentifier": "123",
"DatadeliveyMechanism": "notify",
"MobileOriginatorCallbackReference": {
"url": "http://application.example.com/inbound/notifications/modatanotification/"
},
"AccessiblityCallbackReference": {
"url": "http://application.example.com/inbound/notifications/accessibilitystatusnotification"
}
},
"DeviceList": [{
"ExternalIdentifer": "123456#mydomain.com",
"msisdn": "123456",
"senderName": "Device1",
"MobileOriginatorCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/modatanotification/"
},
"ConfigurationResultCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/configurationResult"
},
"ASreferenceID": "AS000001",
"NIDDduration": "1d"
}]
}
I created the POJO classes and parsed the data using below code
data = new Gson().fromJson(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"), Data.class);
System.out.println(data);
Output:
Data{
deviceCommon=DeviceCommon{
asIdentifier='123'
datadeliveyMechanism='notify'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
accessiblityCallbackReference=http://application.example.com/inbound/notifications/accessibilitystatusnotification
}
deviceList=[DeviceListEntry{
externalIdentifer='123456#mydomain.com'
msisdn='123456'
senderName='Device1'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
configurationResultCallbackReference=http://application.example.com/inbound/notifications/configurationResult
asReferenceID='AS000001'
nidDduration='1d'
}]
}
String jsonInString = gson.toJson(data);
System.out.println("String is"+ jsonInString);
Output:
String is{"DeviceCommon":{"ASIdentifier":"123","DatadeliveyMechanism":"notify","MobileOriginatorCallbackReference":{"url":"http://application.example.com/inbound/notifications/modatanotification/"},"AccessiblityCallbackReference":{"url":"http://application.example.com/inbound/notifications/accessibilitystatusnotification"}},"DeviceList":[{"ExternalIdentifer":"123456#mydomain.com","msisdn":"123456","senderName":"Device1","MobileOriginatorCallbackReference":{"notifyURL":"http://application.example.com/inbound/notifications/modatanotification/"},"ConfigurationResultCallbackReference":{"notifyURL":"http://application.example.com/inbound/notifications/configurationResult"},"ASreferenceID":"AS000001","NIDDduration":"1d"}]}
I need to parse this JSON string to get individual fields like ExternalIdentifier and ASIdentifier.
I tried something like this but it is not working.
JsonObject jobj = new Gson().fromJson(jsonInString, JsonObject.class);
String result = jobj.get("ASIdentifier").toString();
System.out.println("value is"+ result);
Note: ExternalIdentifier is within the array, so I need to loop through the array to find it.
Can you please tell me what I'm doing wrong?
Possible solution:
String result = jobj.get("DeviceCommon").getAsJsonObject().get("ASIdentifier").getAsString();
System.out.println("ASIdentifier: "+ result);
JsonArray jsonArray = jobj.get("DeviceList").getAsJsonArray();
for (JsonElement device : jsonArray ) {
result = device.getAsJsonObject().get("ExternalIdentifer").getAsString();
System.out.println("ExternalIdentifer: "+ result);
}
Output:
ASIdentifier: 123
ExternalIdentifer: 123456#mydomain.com
public static void printJson(JsonElement jsonElement,String key) {
// Check whether jsonElement is JsonObject or not
if (jsonElement.isJsonObject()) {
Set<Entry<String, JsonElement>> ens = ((JsonObject) jsonElement).entrySet();
if (ens != null) {
// Iterate JSON Elements with Key values
for (Entry<String, JsonElement> en : ens) {
// System.out.println("##key is"+en.getKey() + " : ");
printJson(en.getValue(), en.getKey());
// System.out.println(en.getValue().getAsString());
// System.out.println(jsonElement.getAsString());
}
}
}
// Check whether jsonElement is Primitive or not
else if (jsonElement.isJsonPrimitive()) {
// print value as String
System.out.println("###key is"+key);
System.out.println("### value is"+jsonElement.getAsString());
}
else if (jsonElement.isJsonArray()) {
JsonArray jarr = jsonElement.getAsJsonArray();
// Iterate JSON Array to JSON Elements
System.out.println("\n###Array size is"+ jarr.size());
for (JsonElement je : jarr) {
printJson(je,key);
}
}
}

Value 91 at 0 of type java.lang.Byte cannot be converted to JSONObject

I'm getting the following error:
org.json.JSONException: Value 91 at 0 of type java.lang.Byte cannot be converted to JSONObject
And it's because of this line of code:
JSONObject jObj = j.getJSONObject(i);
I'm doing a GET request and I logged it in Android Studio which looks like this:
jsonarray [91,109,111,100,101,108,46,83,116,111,114,101,64,52,57,57,54,102,97,56,44,32,109,111,100,101,108
In the browser it looks like this:
Link to a screenshot: http://i.imgur.com/NTpwbuB.png
I had used a JSONObject, because I want to do later something like this:
String storeName = jObj.getString("STORE NAME");
String street = jObj.getString("STREET");
String city = jObj.getString("CITY");
Here is the code:
public void getSubprises() {
Call<List<Store>> call = subpriseAPI.listStores();
call.enqueue(new Callback<List<Store>>() {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(Response<List<Store>> response, Retrofit retrofit) {
try {
JSONArray j = new JSONArray(response.body().toString().getBytes());
System.out.println("jsonarray "+ j);
for (int i = 0; i < j.length(); i++) {
JSONObject jObj = j.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
just change
JSONArray j = new JSONArray(response.body().toString().getBytes());
to
JSONArray j = new JSONArray(response.body().toString());
i think this is what you want to do.
If this didn't work, then you really don't know what the response body has inside, to learn use System.out.print function to see what response.body().toString() prints.
if it is something like
[
{"STORE_NAME" : "abc", "STREET" : "def"}, {"STORE_NAME" : "asw", "STREET" : "rew" }
]
everything is well. Else you need to change the way you get the jsonobject.
EDIT:
["model.Store#4996fa8","model.Store#949eac1","model.Store#c45f266", ...
this output that you wrote in the comments made me realize that you don't need a JSONArray or anything, Response> response already has the Store objects.
And looking that output, response.body() returns List,
then you can do this to get the outputs
EDIT 2:
java.util.Iterator it=response.body().iterator();
while(it.hasNext())
System.out.println(((Store)it.next()).getStreet());
Above code will only work if the Store object has the method getStreet of course if not you can use st.street or st. then ctrl+space and find the street like label there.

Categories