how to get same fields from jsonArray - java

using gson, I parsed data in json format and now I need to extract the value "dt_txt" and their value "temp" from this data and I don’t understand how to pull and paste them into the collection where the key is "dt_txt" and its value is "temp "
The data that I received: https://imgur.com/a/qAxwEri
package testClassPackage;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class weatherParse {
public static void main(String[] args) throws IOException {
String sURL = "http://api.openweathermap.org/data/2.5/forecast/?q=Odessa,ua&APPID=518a64dd48106aa542464d3bd94d12ce"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
JsonArray message = rootobj.get("list").getAsJsonArray();
for (int i = 0; i < message.size(); i++) {
System.out.println();
}
System.out.println(message);
}
}

iterate over the JsonArray(message I changed to messages here) as JsonElement and get main object from the element then fetch th corresponding temp.
Map<String,String> data = new HashMap<>();
for(JsonElement lst : messages) {
JsonObject lstObject = lst.getAsJsonObject();
JsonObject el = (JsonObject) lstObject.get("main");
System.out.println(lstObject.get("dt_txt").getAsString() +" "+el.get("temp").getAsString());
data.put(lstObject.get("dt_txt").getAsString(), el.get("temp").getAsString());
}

Related

how to convert stringified JSONObject[] to JSONObj[] in java

I have JSONObject[] in stringified format. I need to convert it back to JSONObject[] in java how I can achive that??
Sample Code :
JSONObject[] json = new JSONObject[10];
String jsonStrArray = "[{a:1,b:2,c:3},{a:1,b:2,c:3},{a:1,b:2,c:3}]";
JsonParser parser = new JsonParser();
JsonObject jo = (JsonObject)
parser.parse(strFinalRecord).getAsJsonObject();
json = jo;
Error:
incompatible type
Required : org.json.JsonObject[]
Found : com.google.gson.JsonObject
If it is getting gson.JsonObject how to can I cast it to JsonObject[] ?
Please help me to resolve this issue
The json String you have created is not formatted correctly.
Try the following code.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonTest {
public static void main(String arg[]) throws ParseException {
JSONObject json = new JSONObject();
String jsonStrArray = "[{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"},{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"},{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}]";
JSONParser parser = new JSONParser();
JSONArray jo = (JSONArray) parser.parse(jsonStrArray);
System.out.println(jo);
json.put("key", jo);
System.out.println(json);
}
}
Use JSON-Simple

gson deserialisition of same key different values in json

this is my json event
{
"type":"record",
"name":"Doc",
"doc":"adoc",
"fields":[
{
"name":"id",
"type":"string"
},
{
"name":"user_friends_count",
"type":[
"int",
"null"
]
},
{
"name":"user_location",
"type":[
"string",
"null"
]
}}
am tring to deserialze it event but stuck with same "type" different values like one "type" with "string" value and other with ["string","null"] how can i iterate them?? ths is my code
import java.lang.reflect.Type;
import java.util.ArrayList;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
public class FieldaDeserialisation implements JsonDeserializer<Fields>{
public Fields deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jobj = json.getAsJsonObject();
JsonArray A1 = jobj.get("fields").getAsJsonArray();
JsonPrimitive jtype = null;
String jname = null;
for (int i = 0; i < jobj.size(); i++) {
JsonElement obj = A1.get(i);
JsonObject b1 = obj.getAsJsonObject();
jname = b1.get("name").getAsString();
if (b1.get("type").isJsonArray()) {
JsonArray jarray = b1.get("type").getAsJsonArray();
for (int j = 0; j < jarray.size(); j++) {
jtype = (JsonPrimitive) jarray.get(j);
}
}
else {
jtype = (JsonPrimitive) b1.get("type");
}
}
}
it shows me error on the same line JsonArray A1 = jobj.get("fields").getAsJsonArray(); and on line1 import java.lang.reflect.Type; the error is
Exception in thread "main" java.lang.NullPointerException
at FieldaDeserialisation.deserialize(FieldaDeserialisation.java:18)
at FieldaDeserialisation.deserialize(FieldaDeserialisation.java:1)
at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:72)
at com.google.gson.Gson.fromJson(Gson.java:887)
at com.google.gson.Gson.fromJson(Gson.java:952)
at com.google.gson.internal.bind.TreeTypeAdapter$GsonContextImpl.deserialize(TreeTypeAdapter.java:162)
at JsonDataDeserialisation.deserialize(JsonDataDeserialisation.java:20)
at JsonDataDeserialisation.deserialize(JsonDataDeserialisation.java:1)
at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
at com.google.gson.Gson.fromJson(Gson.java:887)
at JsonMainClass.main(JsonMainClass.java:15)
this is my main deserialisation class
import java.lang.reflect.Type;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
public class JsonDataDeserialisation implements JsonDeserializer<JsonData>{
#Override
public JsonData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
// TODO Auto-generated method stub
JsonObject jobj = json.getAsJsonObject();
String jsontype = jobj.get("type").getAsString();
String jsonname = jobj.get("name").getAsString();
String jsondoc = jobj.get("doc").getAsString();
Fields[] fields = context.deserialize(jobj.get("fields"), Fields[].class);
JsonData jdata = new JsonData();
jdata.setType(jsontype);
jdata.setName(jsonname);
jdata.setDoc(jsondoc);
jdata.setFields(fields);
return jdata;
}
}
and this is main class
import java.io.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
public class JsonMainClass {
public static void main(String []args)throws Exception{
String filepath = "/Users/RAGHU/Desktop/json1 .txt";
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(JsonData.class, new JsonDataDeserialisation());
gsonb.registerTypeAdapter(Fields.class, new FieldaDeserialisation());
Gson gson = gsonb.create();
try(JsonReader reader = new JsonReader(new FileReader(filepath))){
reader.setLenient(true);
JsonData jdata1 = gson.fromJson(reader, JsonData.class);
System.out.println(jdata1);
}
}
}
now this an error i got with a previous way i done
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: This is not a JSON Array.
at com.google.gson.Gson.fromJson(Gson.java:899)
at com.google.gson.Gson.fromJson(Gson.java:952)
at com.google.gson.internal.bind.TreeTypeAdapter$GsonContextImpl.deserialize(TreeTypeAdapter.java:162)
at JsonDataDeserialisation.deserialize(JsonDataDeserialisation.java:20)
at JsonDataDeserialisation.deserialize(JsonDataDeserialisation.java:1)
at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
at com.google.gson.Gson.fromJson(Gson.java:887)
at JsonMainClass.main(JsonMainClass.java:15)
Caused by: java.lang.IllegalStateException: This is not a JSON Array.
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
at FieldaDeserialisation.deserialize(FieldaDeserialisation.java:18)
at FieldaDeserialisation.deserialize(FieldaDeserialisation.java:1)
at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:72)
at com.google.gson.Gson.fromJson(Gson.java:887)
... 7 more
Calling
Fields[] fields = context.deserialize(jobj.get("fields"), Fields[].class);
You are already receiving the Array from this, just parse the json into an Array, then iterate.
JsonArray A1 = json.getAsJsonArray();
Then you can iterate like you seems to do, using the condition on the type of type
To be cleaner, I would use a JsonElement to store the field
JsonElement type = b1.get("type");
if(type.isJsonArray()){
JsonArray array = type.getAsJsonArray();
...//ARRAY
else {
String s = type.getAsString();
...//STRING
}

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 get data from Gson link

this is my code:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.*;
public class GsonDecode {
public static void main (String[] args) throws IOException{
String sURL = "http://pubapi.cryptsy.com/api.php?method=orderdata"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonElement jsonElement = root.getAsJsonObject().get("return");
}
}
I need to get only the "label" of each market from this JSON link. All other info is unnecessarily
Whats the easiest way to do it ?
You can't unless the API is designed for that. Ask API developers for that if it's implementer they'll provide documentation or other URL for that.
Or you can download whole json and get all names like this
JsonElement jsonElement = root.getAsJsonObject().get("return");
Set<Map.Entry<String,JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
for(Map.Entry<String,JsonElement> entry:entries) {
System.out.println(entry.getKey()); //get keys
}

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