2

I have an HTTPResonse that when you get the body looks like this:

{"id":"/Project/34rxq38ntgrvxj7vkzqj8xe7v68"}

I want to get the Id from it to use later and I'm having trouble figuring out how to dynamically say start at Project/ and end at "}. The reason is that the id seems to change in length each time.

I did have

String i = response.getBody().subString(16,45);

but it fails if the length changes. I think I should do something like this to get the index of the last " and then use that as the length but I can't get it to compile.

String i = response.getBody().substring(16, indexofChar('"',16));

The error is:

Method does not exist or incorrect signature: void indexofChar(String, Integer)

What am I doing wrong?

4
  • I would first parse the JSON string, so that I can extract the "value" and store it in a string. And then, I can perform a simple string.split() and extract whatever value I have after second '/' symbol.
    – Arnold Jr.
    Feb 20, 2020 at 18:59
  • 1
    I'm putting this as a comment because I believe Derek F has the best answer but neither of the answers directly answer your question and I think its something that is worth knowing how to do: String i = response.getBody().substring(16, response.getBody().indexofChar('"',16)); Again, Derek's answer is a much better approach for the given use case.
    – gNerb
    Feb 20, 2020 at 19:47
  • @gNerb I could have done more to address the question in the title, but I did indeed answer the "what am I doing wrong" part of the question.
    – Derek F
    Feb 20, 2020 at 19:56
  • This is good for the future, knowing that what I am trying to do while possible with gNerb's part, but more importantly the better approach to the solution in Derek's part. Feb 20, 2020 at 19:58

2 Answers 2

4

indexOfChar() needs to operate on an instance of a string (it's not a static method)

e.g.

String myStr = 'test';
system.debug(myStr.indexOfChar('s'));

Trying to get at your value by substrings is a messy way to go about this though.

Deserializing the JSON, and then using String.split('/') is probably going to be a lot cleaner/readable/reliable

e.g.

public class myClass{
    String id;
}

String res = '{"id":"/Project/34rxq38ntgrvxj7vkzqj8xe7v68"}';
MyClass mc = (MyClass)JSON.deserialize(res, MyClass.class);
List<String> idParts = mc.id.split('/');
System.debug(idParts[2]); // should give you 34rxq38ntgrvxj7vkzqj8xe7v68
1

if you always expect that same estructure you can use response.getbody().substringbetween('t/','"');

Either using substringAfterLast('/').substringBefore('"'); would work too.

Take a look to the String Class documentation: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .