How to get the Content from Specific Field from JSONObject Data - java

i want to get from this JSONObject Data , the content of field "_source",
JSONObject jsonObj =
{
"hits" : [
{
"_index" : "try1",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"target" : {
"br_id" : 0,
"wo_id" : 2,
"process" : [
"element 1",
"element 2"
]
},
"explanation" : {
"an_id" : 1311,
"pa_name" : "micha"
},
"text" : "hello world"
}
}
]
}
the Result should be like bellow ,
String result =
{
"target" : {
"br_id" : 0,
"wo_id" : 2,
"process" : [
"element 1",
"element 2"
]
},
"explanation" : {
"an_id" : 1311,
"pa_name" : "micha"
},
"text" : "hello world"
}
I tried this , but it always could not recognize the "_source" field,
JSONObject main = jsonObj.getJSONObject("hits");
JSONObject content = main.getJSONObject("_source");
JSONObject field = content.getJSONObject("target");
JSONObject["_source"] not found
JSONObject["target"] not found
Please any suggestion or Advices, so i can get the Content from "_source" as Result?
thx.

_source is inside of JSONArray hits, so first get the JSONArray
JSONArray main = jsonObj.getJSONArray("hits");
And then get the first JSONObject from array
JSONObject obj = main.getJSONObject(0);
JSONObject source = obj.getJSONObject("_source"); //now get the _source

Related

How to get a String inside an Object Array using MongoDB Java?

I'm trying to learn MongoDB and I want to get a String inside an Object Array, my MongoDB document is here:
{
"_id" : ObjectId("5f1507fed91e81246c409a59"),
"identification" : "punishment",
"lastID" : 2,
"punishmentsTypes" : [
{
"category" : "OFENSA_JOGADOR",
"reason" : "Ofensa a Jogador",
"group" : [
"HELPER",
"MODERATOR",
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Ofender algum jogador",
"cases" : [
{
"1" : {
"type" : "MUTE",
"duration" : 604800000
}
},
{
"2" : {
"type" : "BAN",
"duration" : 0
}
}
]
},
{
"category" : "FALSIFICACAO",
"reason" : "Falsificação de provas",
"group" : [
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Falsicar provas ao denunciar um jogador em nosso fórum",
"cases" : [
{
"1" : {
"type" : "BAN",
"duration" : 0
}
}
]
},
{
"category" : "HACK",
"reason" : "Hack",
"group" : [
"MODERATOR",
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Uso de cheats ou programas ilícitos",
"cases" : [
{
"1" : {
"type" : "BAN",
"duration" : 7776000000.0
}
},
{
"2" : {
"type" : "BAN",
"duration" : 0
}
}
]
}
],
"unpunishmentTypes" : [
{}
]
}
I've tried this:
MongoCollection<Document> collection = mongoDatabase.getCollection("settings");
BasicDBObject query = new BasicDBObject();
BasicDBObject field = new BasicDBObject();
query.put("id", "punish");
field.put("punishmentsTypes", 1);
field.put("_id", 0);
Document test = collection.find(query).projection(field).first();
assert test != null;
Object object = test.get("punishmentsTypes");
System.out.println(object);
And that's the output:
[Document{{category=OFENSA_JOGADOR}},
Document{{category=FALSIFICACAO}}, Document{{category=HACK}}]
How can I get only the category string, to the output be: OFENSA_JOGADOR, FALSIFICACAO, HACK?
I'm not sure how did you get that result with your query but here is how I get your result:
MongoCollection<Document> collection = mongoDatabase.getCollection("settings");
Document query = new Document();
query.put("identification", "punishment");
Document test = collection.find(query).first();
List<Document> punishmentsTypes = test.getList("punishmentsTypes", Document.class);
for (Document document : punishmentsTypes) {
String category = document.getString("category");
System.out.println(category);
}

how I can get data from JSONObject with Java?

I have an String called inputJson that contains
{"listPruebas": [
{
"nombrePrueba" : "pruebaA",
"id" : 1,
"tipoPrueba" : "PRUEBABASE1",
"elementoBase" : "tipoA",
"listaMarca": [
{
"elemento": "elemento1 ",
"tipo": "ABC",
"cadena": "SFSG34235WF32"
},
{
"elemento":"elemento2",
"tipo":"DEF",
"cadena":"DJRT64353GSDG"
},
{
"elemento" : "elemento3",
"formato ":"JPG"
}
]},
{
"nombrePrueba" : "pruebaB",
"id" : 2,
"tipoPrueba" : "PRUEBABASE2",
"elementoBase" : "imagenPrueba",
"listaMarca2": [
{
"elemento" : "imagen",
"tipo": "tipo5",
"cadena": "iVBORw0KGgoAAAANSUhEUgAAAgAAAA"
}
]
}
],
"listaBuscar":
[
{
"tipoBusqueda":"busqueda1",
"id" : 1,
"operacion" : "operacion1",
"valor" : "12"
},
{
"tipoBusqueda":"binario",
"id" : 2,
"operacion" : "operacion2",
"valor" : "13"
},
{
"tipoFiltro":"numerico",
"id" : 31,
"operacion" : "MENOR_QUE",
"valor" : "1980",
"intervalo" : 1
}
]
}
and I converted the String to JSONObject of this way
JSONObject object = new JSONObject(inputJson);
and I got this
jsonObject::{"listaBuscar":[{"valor":"12","id":1,"operacion":"operacion1","tipoBusqueda":"busqueda1"},{"valor":"13","id":2,"operacion":"operacion2","tipoBusqueda":"binario"},{"tipoFiltro":"numerico","intervalo":1,"valor":"1980","id":31,"operacion":"MENOR_QUE"}],"listPruebas":[{"listaMarca":[{"tipo":"ABC","elemento":"elemento1","cadena":"SFSG34235WF32"},{"tipo":"DEF","elemento":"elemento2","cadena":"DJRT64353GSDG"},{"elemento":"elemento3","formato":"JPG"}],"elementoBase":"tipoA","tipoPrueba":"PRUEBABASE1","nombrePrueba":"pruebaA","id":1},{"elementoBase":"imagenPrueba","tipoPrueba":"PRUEBABASE2","listaMarca2":[{"tipo":"tipo5","elemento":"imagen","cadena":"iVBORw0KGgoAAAANSUhEUgAAAgAAAA"}],"nombrePrueba":"pruebaB","id":2}]}
and now I need to extract information but I dont know how to do, for example I try this
object.getString("elemento1");
but I got this error
Caused by: org.json.JONException: JSONObject["elemento1"] not found
help me please
You can't get a nest JSON object from the top level. It's like a treemap. You need to convert it into a java object or get it level by level.
check this post, a lot of ways.
You json contains two json arrays, fetch them as -
JSONArray listaBuscArray = jsonObj.getJSONArray("listaBuscar");
JSONArray listPruebasArray = jsonObj.getJSONArray("listPruebas");
Now you can process and use them as -
for(int i=0; i<listaBuscArray.length; i++){
JSONObject obj = listaBuscArray.getJSONObject(i);
.... your logic
}

Get value out JSON Object containing JSON arrays

How can I get the value of "distance" out of the following JSON object with java?
{
"destination_addresses" : [ "New York City, New York, Verenigde Staten" ],
"origin_addresses" : [ "Washington D.C., District of Columbia, Verenigde Staten" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "225 mijl",
"value" : 361714
},
"duration" : {
"text" : "3 uur 51 min.",
"value" : 13877
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I tried:
json.getJSONArray("rows").getJSONObject(0).getJSONObject("distance").toString();
But I always get org.json.JSONException: JSONObject["distance"] not found.
I think you are missing the second array "elements", you find array "row" so get object 0, in object 0 you need to find the "elements" array then take the object 0 again, so you can get the "distance" object.
Try this:
json.getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").toString();
Again, I think. I hope this helped you.
Use java-json.jar
Convert JSON String to object and fetch the element.
You can refer this.
Try this:
package Sample;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestMain
{
public static void main(String[] args) throws JSONException
{
String s="{ \"destination_addresses\" : [ \"New York City, New York, Verenigde Staten\" ], \"origin_addresses\" : [ \"Washington D.C., District of Columbia, Verenigde Staten\" ], \"rows\" : [ { \"elements\" : [ { \"distance\" : { \"text\" : \"225 mijl\", \"value\" : 361714 }, \"duration\" : { \"text\" : \"3 uur 51 min.\", \"value\" : 13877 }, \"status\" : \"OK\" } ] } ], \"status\" : \"OK\"} ";
JSONObject jsonObj = new JSONObject(s);
JSONArray array= (JSONArray) jsonObj.get("rows");
JSONObject jsonObj2 =(JSONObject) array.get(0);
JSONArray array2= (JSONArray)jsonObj2.get("elements");
JSONObject jsonObj3 =(JSONObject) array2.get(0);
System.out.println(jsonObj3.get("distance"));
}
}
OUTPUT:
{"text":"225 mijl","value":361714}

Error in Creating JSON object

I'm getting an JSON array as a string value and I need to create a JSON object using that. array code is like this.
{"eventsList" : [
"requestId" : "82334-adf86d-8bac8ef-289c"
events:[
{
"eventType" : "receiveLocation_Event",
"externalId" : "973af2f8-820b-457b-89c2",
"description" : "Test Event",
"whenOccurred" : "06-Aug-2013 07.15.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"locationAccuracy" : "10",
"attr2" : "value2"
},
"count" : "2"
},
{
"eventType" : "SEND_SMS_sendSmsEvent",
"externalId" : "45af4f8-87-4f42b-832abc",
"description" : "Another Test Event",
"whenOccurred" : "06-Aug-2013 08.16.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"messageLength" : "135",
"attrX" : "valueX"
},
"count" : "1"
}
]
}
]
}
i try to create an JSON object using folowing code line
SONObject jsonObject = new JSONObject(string);
I'm getting an error when i run this.
org.json.JSONException: Expected a ',' or ']' at character 35
at org.json.JSONTokener.syntaxError(JSONTokener.java:413)
at org.json.JSONArray.<init>(JSONArray.java:143)
at org.json.JSONTokener.nextValue(JSONTokener.java:351)
at org.json.JSONObject.<init>(JSONObject.java:206)
at org.json.JSONObject.<init>(JSONObject.java:420)
Please help me to solve this issue.
There are several mistakes.
After [ a list of comma-separated values is expected, but you have a colon after "requestId". You probably meant for the [ on line 1 to be a {.
Given the last issue, you probably want a comma after "82334-adf86d-8bac8ef-289c"
If you drop your text into an online JSON formatter and validator, such as this one it will point out all your errors.
Problem is here:
...
"requestId" : "82334-adf86d-8bac8ef-289c"
events:...
You forgot some punctuation:
...
"requestId" : "82334-adf86d-8bac8ef-289c",
"events":......
Use this instead this is JSON syntax. All keys are strings.
This is how the String should be;
{"eventsList" : [
{"requestId" : "82334-adf86d-8bac8ef-289c"},
{ "events":[
{
"eventType" : "receiveLocation_Event",
"externalId" : "973af2f8-820b-457b-89c2",
"description" : "Test Event",
"whenOccurred" : "06-Aug-2013 07.15.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"locationAccuracy" : "10",
"attr2" : "value2"
},
"count" : "2"
},
{
"eventType" : "SEND_SMS_sendSmsEvent",
"externalId" : "45af4f8-87-4f42b-832abc",
"description" : "Another Test Event",
"whenOccurred" : "06-Aug-2013 08.16.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"messageLength" : "135",
"attrX" : "valueX"
},
"count" : "1"
}
]
}
]
}
the requestId and event must be like this: {"requestId" : "82334-adf86d-8bac8ef-289c"},
{ "events":
And also there must be closing } after closing the inner JSONArray ]

Java JSONObject get children

i want to create gmaps on my website.
I found, how to get coordinates.
{
"results" : [
{
// body
"formatted_address" : "Puławska, Piaseczno, Polska",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 52.0979041,
"lng" : 21.0293984
},
"southwest" : {
"lat" : 52.0749265,
"lng" : 21.0145743
}
},
"location" : {
"lat" : 52.0860667,
"lng" : 21.0205308
},
"location_type" : "GEOMETRIC_CENTER",
"viewport" : {
"northeast" : {
"lat" : 52.0979041,
"lng" : 21.0293984
},
"southwest" : {
"lat" : 52.0749265,
"lng" : 21.0145743
}
}
},
"partial_match" : true,
"types" : [ "route" ]
}
],
"status" : "OK"
}
I want to get:
"location" : {
"lat" : 52.0860667,
"lng" : 21.0205308
},
From this Json.
I decided to user json-simple
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
My code is:
String coordinates = //JSON from google
JSONObject json = (JSONObject)new JSONParser().parse(coordinates);
And i can get the first children: "results"
String json2 = json.get("results").toString();
json2 display correct body of "results"
But i cannot get "location" children.
How to do it ?
Thanks
I think you need to cast the call to json.get("results") to a JSONArray.
I.e.
String coordinates = //JSON from google
JSONObject json = (JSONObject)new JSONParser().parse(coordinates);
JSONArray results = (JSONArray) json.get("results");
JSONObject resultObject = (JSONObject) results.get(0);
JSONObject location = (JSONObject) resultObject.get("location");
String lat = location.get("lat").toString();
String lng = location.get("lng").toString()
The trick is to look at what type the part of the json you're deserializing is and cast it to the appropriate type.
about this link
com.google.gson.JsonParser#parse(java.lang.String) is now deprecated
so use com.google.gson.JsonParser#parseString, it works pretty well
Kotlin Example:
val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject
Java Example:
JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();

Categories

Resources