I am getting response from server in JSONArray format. I am not able to retrieve the contents of array also my JSONArray has no Square brackets.
I am passing the response in php as json_encode($array) in server side
response {
community = “worker”
communitystr = "<null>";
workspace = abs;
email = "<null>";
admin = false;
persona = "<null>";
userinfo = {
info = {
contact1 = {
firstname = “jon”;
lastname = “Doe”
phone = “9885678905”;
objectname = contact;
id = 9;
};
event1 = {
eventname = “party”;
description = "";
order = 6;
id = 4;
objectname = events;
};
files = {
filename = “sample”;
description = "";
order = 11;
id = 11;
objectname = files;
};
};
};
};
I checked many links and all have used JSONObject(). But same is not working for me.
How do I get each values in this JSON Response ?
You have to use
: instead of =
, instead of ;
...
Watch out following format:
{
"Herausgeber": "Xema",
"Nummer": "1234-5678-9012-3456",
"Deckung": 2e+6,
"Waehrung": "EURO",
"Inhaber":
{
"Name": "Mustermann",
"Vorname": "Max",
"maennlich": true,
"Hobbys": [ "Reiten", "Golfen", "Lesen" ],
"Alter": 42,
"Kinder": [],
"Partner": null
}
}
Your code seems like to be more JavaScript-Object like :-)
Your response is not valid JSON object.
You can validate the JSON via some online tool, like http://jsonlint.com/
Full specification can be found in RFC 7159 https://www.rfc-editor.org/rfc/rfc7159.
Basically you should look how to encode the values into JSON format in correct way. For that you can refer to PHP Array to JSON Array using json_encode();
Related
I'm creating a kotlin app. I have an issue with mediaMetadataCompat. Maybe I have to put data to extras? I put data like this
audios = allAudios!!.map { audio ->
MediaMetadataCompat.Builder()
.putString(METADATA_KEY_WRITER, audio.writer._id)
.putString(METADATA_KEY_ARTIST, audio.writer.name)
.putString(METADATA_KEY_DISPLAY_SUBTITLE, audio.writer.name)
.putString(METADATA_KEY_MEDIA_ID, audio._id)
.putString(METADATA_KEY_TITLE, audio.title)
.putString(METADATA_KEY_DISPLAY_TITLE, audio.title)
.putString(METADATA_KEY_DISPLAY_ICON_URI, audio.writer.image)
.putString(METADATA_KEY_DATE, audio.createdAt)
.putString(METADATA_KEY_MEDIA_URI, audio.filePath)
.putString(METADATA_KEY_DISPLAY_DESCRIPTION, audio.description)
.build()
}
Get it like this
fun MediaMetadataCompat.toAudio(): Audio? {
return let {
Audio(
_id = it.description.mediaId ?: "",
title = it.description.title.toString(),
filePath = it.description.mediaUri.toString(),
description = it.description.description.toString(),
writer = User(
_id = it.description.extras?.getString("writerId").toString(),
name = it.description.subtitle.toString(),
image = it.description.iconUri.toString()
),
tags = listOf("Shit"),
listened = 1,
language = "en",
isForKids = false,
duration = 70,
createdAt = "2020:01:01"
)
}
}
It only gives my title, icon_uri, media_uri and media_id
Sharing a small part of my code:
Below is building object of MediaMetaDataCompat. I am adding couple of data there and have used in different parts of app.
var media = MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, data.id.toString())
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, data.artist_name)
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, data.title)
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, data.audio_path)
.putString(MediaMetadataCompat.METADATA_KEY_DATE, data.track_year)
.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI, data.image_path)
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, data.duration.toLong())
.build()
mediaItem is object of MediaMetadataCompat and that is how I am getting values of the fields which was added to object.
mediaItem is object of MediaMetadataCompat
var artist = mediaItem.bundle.getString(MediaMetadataCompat.METADATA_KEY_ARTIST)!!
var title = mediaItem.bundle.getString(MediaMetadataCompat.METADATA_KEY_TITLE)!!
var duration = mediaItem.bundle.getLong(MediaMetadataCompat.METADATA_KEY_DURATION)!!
var icon = mediaItem.bundle.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI)!!
JSON values that I get from server:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
Getting the result as 'response' after connection and I am able to show my JSON string results on the screen.
JSONObject json = new JSONObject(response);
String status = json.getString("Status");
String message = json.getString("Message");
String result = json.getString("Result");
responseView.setText("Status" + status+ "Message" + message" + Result" + result);
I am okay the results of "Status" and "Message" but not with "Result" because want to separate "Result" objects as and able use each of them as objects.
For example:
When I type OB in my app, I will get the result S.C. Blue Air
Instead of :
String result = json.getString("Result");
use
if(json.get("Result") instanceof JSONObject){
JSONObject object = (JSONObject) json.get("Result");
//do what you want with JSONObject
String ob = object.get("0B");
}
If you want to store it some way you can put it to Map or create object if always it is same data
You can use some libraries such as Gson (Google) or Moshi (Square)
Those libraries allows you to declare your model as a plain java class (commonly called POJOS) annotated in some way that this libraries bind your properties in the JSON to your java properties.
In your case:
JSON:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
MODEL:
public class MyCallResponse {
#SerializedName("Status")
int status;
#SerializedName("Message")
String message;
#SerializedName("Result")
Result result;
}
public class Result {
#SerializedName("0B")
String b;
#SerializedName("0Y")
String y;
#SerializedName("0X")
String x;
}
In this case, with Gson you can do:
MyCallResponse response = new Gson().fromJson(json, MyCallResponse.class);
Log.i("Response b", response.result.b);
Look at the documentation for more information about both libraries.
try this :
JSONObject json = new JSONObject(response);
JSONObject resultObj = json.getJSONObject("Result");
String OB = resultObj.getString("OB");
Try this
String base = ""; //Your json string;
JSONObject json = new JSONObject(base);
JSONOBject resultJson = json.getJSONObject("Result");
// Get all json keys "OB", "OY", "1X" etc in Result, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = resultJson.entrySet();
Iterator iterator = entrySet.iterator();
for (int j = 0; j < entrySet.size(); j++) {
String key = null; //key = "OB", "OY", "1X" etc
try {
Map.Entry entry = (Map.Entry) iterator.next ();
key = entry.getKey ().toString ();
//key = "OB", "OY", "1X" etc
}
catch (NoSuchElementException e) {
e.printStackTrace ();
}
if (!TextUtils.isEmpty (key)) {
Log.d ("JSON_KEY", key);
String value = resultJson.getString(key);
//for key = "0B", value = "S.C. Blue Air"
//for key = "0Y", value = "FlyYeti"
//for key = "1X", value = "Branson Air"
}
}
It works with any array with dynamic json key.
Don't forget to accept the answer & upvote if it works.
I'm trying to parse json with an edittext, make it match for an id, and load the data it carries in textview. Im not really sure how to go about this, whether im using the right JSON, or if im using the right way to determine the most efficiet way to handle this. When i enter '5' in the edittext, i get the error mentioned below:
Error:
org.json.JSONException: No value for id
The JSON from url being parsed:
{
"id": "5",
"first_name": "Larry",
"last_name": "Gonzales",
"email": "lgonzales4#msu.edu",
"country": "Japan",
"ip_address": "242.198.195.241"
}
Java:
try {
JSONObject e = new JSONObject();
JSONObject jsonobjectidloader = e.getJSONObject(TAG_ID);
if (jsonobjectidloader.equals(xyz)){
uid.setText(id3);
id3 = jsonobjectidloader.getString(TAG_ID);
name1.setText(fname);
fname = jsonobjectidloader.getString(TAG_FIRST_NAME);
name2.setText(lname);
lname = jsonobjectidloader.getString(TAG_LAST_NAME);
email1.setText(email);
email = jsonobjectidloader.getString(TAG_EMAIL);
ipaddres.setText(ipa);
ipa = jsonobjectidloader.getString(TAG_IP);
cou.setText(country);
country = jsonobjectidloader.getString(TAG_COUNTRY);
I hope you guys can help me with this, im really stumped right now.
JSONObject e = new JSONObject(response.toString());
String id3 = e.getString(TAG_ID);
Response is your json from server
Use following code.
JSONObject jsonobjectidloader= new JSONObject(YOUR_JSON_STRING);
if (jsonobjectidloader.equals(xyz)){
id3 = jsonobjectidloader.getString(TAG_ID);
uid.setText(id3);
fname = jsonobjectidloader.getString(TAG_FIRST_NAME);
name1.setText(fname);
lname = jsonobjectidloader.getString(TAG_LAST_NAME);
name2.setText(lname);
email = jsonobjectidloader.getString(TAG_EMAIL);
email1.setText(email);
ipa = jsonobjectidloader.getString(TAG_IP);
ipaddres.setText(ipa);
country = jsonobjectidloader.getString(TAG_COUNTRY);
cou.setText(country);
just use it as
String json = '{"id":"5","first_name":"Larry","last_name":"Gonzales","email":"lgonzales4#msu.edu","country":"Japan","ip_address":"242.198.195.241"}';
e = new JSONObject(json);
.....
you need to actually provide the string to jsonboject constructor as argument.
We have to parse a json structure similar to below.
project {
header {
}
pool {
}
cmp {
name = "";
id = "";
desc = "";
cmp [
{
name = "";
id = "";
desc = "";
}
{
name = "";
id = "";
desc = "";
}
{
name = "";
id = "";
desc = "";
cmp [
{
name = "";
id = "";
desc = "";
}
}
}
}
The issue is, cmp element is present in the json infinitly (and it is recursive too).
The cmp element contains lots of properties other than name, id and desc. But we need only name, id and desc to extract from the jSON.
I can able to parse the JSON string using com.json.parsers.JSONParser. But populating the parsed JSON to a model class/bean class is not working. It may be a simple logic. But I cannot. Please help...
The json file is generated as an output of one modeling software.
I want to parse this, using java. Can somebody help me to parse this?
Hope I have explained the issue correctly. Your help will be helpful for us.
You can do this with Jackson, just create your object with all the fields that may or may not be present in the message. All the fields not present in the message will end up as null (or default value for primitives) in the resulting object.
Just have the object contain a copy of itself and that will handle the recursion
#XmlRootElement
public class Foo {
Foo recursiveFoo; // will be null or another instance of Foo
int intData; // Will be 0 or an integer value
String strData; // Will be null or a String value
// Getters and setters here
}
Take a look at Google Gson library. With it you can do things like:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
//(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
//==> json is {"value1":1,"value2":"abc"}
//(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
//==> obj2 is just like obj
I have following file/string/data.I want to parse it in key value pair for core java or Android.It is ".ini" file,but parser like ini4j,java Properties class are not working for this.Can anybody please help in selecting parser and Implementing steps.
version = "1.5";
client = "demo";
key2 = "Key2_value";
Providers = (
{
Name = "DEMO_PROVIDER";
Version = 3845678;
key3="key_3_value"
PAs = [ "Pa value 1", "Pa value 2", "Pa value 3" ];
LogLevel = "DEBUG";
Server = "www.stackoverflow.com";
Services = (
{
Percent = 10;
certFormat = "text";
key4 = false;
key5 = "KEY5_NAME";
Uri = "www.stackoverflow.com";
Key6= "No";
key7= "R11";
Users = [ "swapnil#test.local" ];
} );
} );
Which parser is to be used for this kind of file.