Conditionally getting json data using java - java

below is my code where Im trying to check id id =101 and getting the name= Pushkar assosiated with the id=101.But the code is not working as expected.
import org.json.simple.JSONArray;
import org.json.JSONException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class A6 {
public static void main(String[] args) throws ParseException, JSONException{
String out1="{\"Employee\":[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}";
//System.out.println(out1);
JSONParser parser=new JSONParser();
JSONObject obj=(JSONObject)parser.parse(out1);
//System.out.print(obj);
JSONArray jarr=(JSONArray)obj.get("Employee");
//System.out.print(jarr);
for (int i=0;i<jarr.size();i++)
{
JSONObject jobj=(JSONObject)jarr.get(i);
String ID1=(String)jobj.get("id");
System.out.println(ID1);
if(ID1!=null && out1.equals(ID1))
{
System.out.println("NAME"+jobj.get("name"));
}
}
}}

why do you compare out1 with ID1? Either you want to check if out1 contains ID1 (which is not very meaningfull, as you retrieve ID1 from out1) or you want to verify that ID1 equals 101. In that case you would rather want to say something like:
if(ID1!=null && "101".equals(ID1))
{
System.out.println("NAME"+jobj.get("name"));
}

Try to change if condition like this:
if(ID1!=null && out1.contains(ID1))
{
System.out.println("NAME"+jobj.get("name"));
}
Thanks.

Related

Map JSON string or JSON array to String in Java object [duplicate]

This question already has answers here:
Make Jackson interpret single JSON object as array with one element
(3 answers)
Deserializing json to pojo where json field has different data types
(2 answers)
Closed 1 year ago.
I have a JSON created by Elixir class which has a field which can be string or array:
field :logs, {:array, :string}
If anyone doesn't get this it will be like
{"logs" : "some log 1"}
or
{
"logs": ["some log 1", "some log 2"]
}
I have a Java field mapped for this:
#JsonProperty("logs")
private String logs;
This mapping works only when the logs comes as a String, but fails if the logs comes as array with error saying it will not be able to convert START_ARRAY to string.
How to serialize the field if it comes as array and store it as a comma separated string?
I see in tags that you use Jackson for parsing. This means you need to write and register with Jackson a custom deserializer for your logs field.
An example of such solution:
package tmp;
import java.io.IOException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ValueNode;
public class JacksonDemo {
public static class LogHolder {
#JsonProperty("logs")
#JsonDeserialize(using = ArrayOrStringJsonDeserializer.class)
private String logs;
#Override
public String toString() {
return "LogHolder(logs=" + logs + ")";
}
}
public static class ArrayOrStringJsonDeserializer extends JsonDeserializer<String> {
#Override
public String deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = (JsonNode) jsonParser.readValueAsTree();
if (node.isValueNode()) {
ValueNode valueNode = (ValueNode) node;
if (valueNode.isTextual()) {
return valueNode.textValue();
}
} else if (node.isArray()) {
ArrayNode arrayNode = (ArrayNode) node;
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(arrayNode.iterator(), Spliterator.ORDERED), false)
.map(JsonNode::textValue)
.collect(Collectors.joining(", "));
}
throw MismatchedInputException.from(jsonParser, String.class,
"Expected node to be of type String or array, but got " + node.getNodeType().toString());
}
}
public static void main(String args[]) throws Exception {
String[] docs = { "{\"logs\" : \"some log 1\"}", "{\"logs\": [\"some log 1\", \"some log 2\"]}" };
ObjectMapper om = new ObjectMapper();
for (String doc : docs) {
System.out.println(om.readValue(doc, LogHolder.class));
}
}
}
Result of executing this code:
LogHolder(logs=some log 1)
LogHolder(logs=some log 1, some log 2)

Properties file to complex JSON string [Java/Spring]

I'm creating a Spring application on backend and my main goal is to manage properties (add/update/delete) in *.properties file. I want to convert this file to JSON and then manipulate it from UI application.
Is there any possibility to convert structure like this:
a.x=1
a.y=2
b.z=3
To JSON like this:
{
"a": {
"x": 1,
"y": 2
},
"b": {
"z": 3
}
}
I found solution to use GSON library, but it creates for me flat structure, not hierarchical, code I used:
Properties props = new Properties();
try (FileInputStream in = new FileInputStream(classPathResource.getFile())) {
props.load(in);
}
String json = new GsonBuilder().enableComplexMapKeySerialization().create().toJson(props);
Is here someone who was facing same problem and maybe found a working project for this? Maybe GSON library can do that?
This solution does involve loads of work, but you will get what you want to achieve using the below code, basically, the idea is to split the key based on the single dot and then create a JsonObject if the same first key is found.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;
import org.json.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class SOTest {
public static void main(String[] args) throws IOException {
JSONObject jsonObject = new JSONObject();
FileReader fileReader = new FileReader(new File("C:\\Usrc\\main\\java\\Sample.properties"));
Properties properties = new Properties();
properties.load(fileReader);
Iterator<Entry<Object, Object>> iterator = properties.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Object, Object> entry = iterator.next();
String value = (String) entry.getKey();
String[] values = value.split("\\.");
JSONObject opt = jsonObject.optJSONObject(values[0]);
if(opt!=null) {
opt.put(values[1],entry.getValue());
}else {
JSONObject object = new JSONObject();
object.put(values[1], entry.getValue());
jsonObject.put(values[0], object);
}
}
System.out.println(jsonObject.toString());
}
}
Output
{"a":{"x":"1","y":"3"},"b":{"z":"10"}}

parse json string using simple-json

I have read the posts that appeared to be the same as my question but I must be missing something. My environment is Eclipse Mars. My JAVA is 1.7 and I have imported json-simple. I simply wish to parse the json that is returned from my web service. I control the web service if I need to modify its output. I see the json in arg[0] as noted below however the Object obj is null as of course is the JSONArray array. I know that I am missing something basic but I am stumped and a bit tired.
Here is the returned json:
[{"$id":"1","NumberID":121183,"PortfolioID":718,"PropertyID":14489,"Adsource":17287,"PlanTypeID":1,"GreetingFile":"HolidayGreeting.wav","PromptFile1":"senior.leasing.first.wav","Accepts1":2,"PromptAction_ID1":1,"PromptFile2":"Default.wav","Accepts2":2,"PromptAction_ID2":1,"PromptFile3":"Default.wav","Accepts3":2,"PromptAction_ID3":1,"PromptFile4":"Default.wav","Accepts4":2,"PromptAction_ID4":1,"PromptFile5":"Default.wav","Accepts5":2,"PromptAction_ID5":1,"HoldMsgFile1":"SpectrumHold.wav","HoldMsgFile2":"Default.wav","Destination1":15197,"Destination2":15024,"Destination3":0,"UIType_ID":16,"RingCount":0,"Enabled":true,"Spanish":false,"HoldMusicFile":"Hold_Music.wav","Template_ID":41,"FrontLineForward":true,"DisclaimerFIle":"1Silence.wav"}]
Here is the parse code employing json-simple:
package parser;
import org.json.simple.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
public class JsonParser
{
private static JSONObject _jsonInput;
public static void main(String[] args)
{
//TODO
try{
JSONParser parser = new JSONParser();
Object obj = JSONValue.parse(args[0]);
JSONArray array=(JSONArray)obj;
String name = array.get(3).toString();
System.out.println(obj);
}
catch(Exception e){
e.printStackTrace();
}
}
}
The size of the array different than the index used
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(args[1]));
JSONArray array=(JSONArray)obj;
if (array.size() > 3)
String name = array.get(3).toString();

How to parse items from JSON string in Java

I have this code and I tried to getting items from this JSON string but it failed.
I'm parsing the Json string from remote host.
package selectDB;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.*;
public class selectDB
{
public static void main(String[] args) throws IOException, ParseException
{
String s = "";
URL u = new URL("http://192.168.3.1/android/select.php");
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
for(String line; (line = reader.readLine()) != null;)
{
s+=line;
}
System.out.println(s);
}
}
the result is
{"result" : "true" , "messages" : [{"id":"866343023633578","latitute":"27","longitude":"31","number_phone":"01113171374"},{"id":"352168066354050","latitute":"27","longitude":"31","number_phone":"202222"},{"id":"50","latitute":"50","longitude":"100","number_phone":"50"},{"id":"110","latitute":"50","longitude":"50","number_phone":"110"},{"id":"120","latitute":"27","longitude":"31","number_phone":"120"},{"id":"130","latitute":"28","longitude":"29","number_phone":"120"},{"id":"140","latitute":"30","longitude":"40","number_phone":"140"},{"id":"800","latitute":"60","longitude":"30","number_phone":"800"},{"id":"353629054230064","latitute":"70","longitude":"80","number_phone":"120"}]}
Please help!
U can use the JsonReader class.
try (JsonReader in = Json.createReader(r)) {
JsonObject jsonObject= in.readObject();
YourObject obj = new YourObject();
obj.setSomething(jsonObject.getString("something", null));
// "something" is the key in the json file, null is the default
// when "something" was not found
} catch (JsonException | ClassCastException ex) {
throw new BadRequestException("Invalid Json Input");
}
you can use the Google Library GSON as well, it is easy to use and self explaining.
https://code.google.com/p/google-gson/
Gson Goals
Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
Allow pre-existing unmodifiable objects to be converted to and from JSON
Extensive support of Java Generics
Allow custom representations for objects
Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

Parsing JSON data in Java

I want to parse the some data from this page:
http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json
The data I want to parse is the titles however I am unsure how I can extract the data. This is what I have done so far:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Test
{
public Test() { }
public static void main(String[] args)
{
URL url;
HttpURLConnection connection = null;
InputStream is = null;
JSONParser parser = new JSONParser();
try
{
url = new URL("http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
is = connection.getInputStream();
BufferedReader theReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String reply;
while ((reply = theReader.readLine()) != null)
{
System.out.println(reply);
Object obj = parser.parse(reply);
JSONObject jsonObject = (JSONObject) obj;
String title = (String) jsonObject.get("time");
System.out.println(title);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This just returns null. Can anybody tell me what I need to change? Thanks.
If you read the javadoc of JSONObject#get(String) which is actually HashMap.get(String), it states
Returns: the value to which the specified key is mapped, or null if
this map contains no mapping for the key
Your JSON does not contain a mapping for the key time.
Edit:
If you meant title instead of time, take this extract of the JSON
{"schedule":{"service":{"type":"radio","key":"radio1","title":"BBC Radio 1",...
You need to first get schedule as a JSONObject, then service as a JSONObject, and then title as a normal String value. Apply this differently depending on the type of JSON value.
use something like JSONGen to better understand your data structures, maybe even map your data to the generated objects using google-gson library

Categories