Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

MarKteus

[Resolvido] Como ler JSON no ASP ?

Recommended Posts

Olá

 

Preciso obter dados Json via ASP e até já consegui porém de dois endereços no mesmo servidor e operando sob IIS7.

Quando os dados provem de outro servidor por exemplo um endereço localizado em APACHE dá o erro MSXMLError ou seja não consigo nada.

Será porque a requisição é feita via ASP rodando sobre IIS e a resposta provem do APACHE TOMCAT ? E o MSXML por ser um componente microsoft apresenta este conflito? Como devo me proceder neste caso? Existe algum componente similar que posso utilizar no lugar do MSXML?

Lembrando que uma página ASP é que deve obter o resultado que vem de um serviço rodando sobre Apache

 

No aguardo

Compartilhar este post


Link para o post
Compartilhar em outros sites

use assim:

 

para ler:

 

<!--#include virtual="/aspJSON.asp" -->

<%
Set oJSON = New aspJSON

'Load JSON string
oJSON.loadJSON(jsonstring)

'Get single value
Response.Write oJSON.data("firstName") & "<br>"

'Loop through collection
For Each subItem In oJSON.data("address")
    Response.Write subItem & ": " & _
    oJSON.data("address").item(subItem) & "<br>"
Next

'Update/Add value
oJSON.data("firstName") = "James"

'Return the object
Response.Write oJSON.JSONoutput()
%>

input

 

{
  "firstName": "John",
  "lastName" : "Smith",
  "age"      : 25,
  "address"  :
  {
    "streetAddress": "21 2nd Street",
    "city"         : "New York",
    "state"        : "NY",
    "postalCode"   : "10021"
  },
  "phoneNumber":
  [
    {
        "type"  : "home",
        "number": "212 555-1234"
      },
      {
        "type"  : "fax",
        "number": "646 555-4567"
    }
  ]
}

e para escrever

 

<!--#include virtual="/aspJSON.asp" -->
<%
Set oJSON = New aspJSON

'Write single value
oJSON.data("familyName") = "Smith"

'Make collection
Set oJSON.data("familyMembers") = oJSON.Collection()

'Add instances to collection
Set newitem = oJSON.AddToCollection(oJSON.data("familyMembers"))
newitem.add "firstName", "John"
newitem.add "age", 41
newitem.add "gender", "Male"

Set newitem = oJSON.AddToCollection(oJSON.data("familyMembers"))
newitem.add "firstName", "Suzan"
newitem.add "age", 38
newitem.add "gender", "Female"

Set newitem = oJSON.AddToCollection(oJSON.data("familyMembers"))
newitem.add "firstName", "John Jr."
newitem.add "age", 11
newitem.add "gender", "Male"

'Return the object
Response.Write oJSON.JSONoutput()
%>
[OUTPUT]
{
  "familyName": "Smith",
  "familyMembers":
  [
    {
      "firstName": "John",
      "age": 41,
      "gender": "Male"
    },
    {
      "firstName": "Suzan",
      "age": 38,
      "gender": "Female"
    },
    {
      "firstName": "John Jr.",
      "age": 11,
      "gender": "Male"
    }
  ]
}

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Obrigado pela atenção xanburzum

Mas o que fazer quando o retorno Json provém de um link externo, ou seja, de uma aplicação Java por exemplo ?

 

http://service.quaqua.com.br/qualquercoisa/arqjson.json?id=00896?city=novadeli?pais=farway

 

Eu já havia feito o exemplo que vc me mandou, mas no meu ambiente corre tudo bem o problema é quando utilizo o link real, de onde preciso realmente pegar os dados e utilizá-los na minha aplicação

Compartilhar este post


Link para o post
Compartilhar em outros sites

vc precisa criar uma função que recebe a resposta do servidor, analisa o objeto JSON string em um objeto JSON usando o utilitário do arquivo de métodos JSON.Você deve verificar se o response text is null ou não,antes de fazer qualquer análise!

Compartilhar este post


Link para o post
Compartilhar em outros sites
Em 2013-10-20 at 22:42, xanburzum disse:

use assim:

 

para ler:

 


<!--#include virtual="/aspJSON.asp" -->

<%
Set oJSON = New aspJSON

'Load JSON string
oJSON.loadJSON(jsonstring)

'Get single value
Response.Write oJSON.data("firstName") & "<br>"

'Loop through collection
For Each subItem In oJSON.data("address")
    Response.Write subItem & ": " & _
    oJSON.data("address").item(subItem) & "<br>"
Next

'Update/Add value
oJSON.data("firstName") = "James"

'Return the object
Response.Write oJSON.JSONoutput()
%>

input

 


{
  "firstName": "John",
  "lastName" : "Smith",
  "age"      : 25,
  "address"  :
  {
    "streetAddress": "21 2nd Street",
    "city"         : "New York",
    "state"        : "NY",
    "postalCode"   : "10021"
  },
  "phoneNumber":
  [
    {
        "type"  : "home",
        "number": "212 555-1234"
      },
      {
        "type"  : "fax",
        "number": "646 555-4567"
    }
  ]
}

e para escrever

 


<!--#include virtual="/aspJSON.asp" -->
<%
Set oJSON = New aspJSON

'Write single value
oJSON.data("familyName") = "Smith"

'Make collection
Set oJSON.data("familyMembers") = oJSON.Collection()

'Add instances to collection
Set newitem = oJSON.AddToCollection(oJSON.data("familyMembers"))
newitem.add "firstName", "John"
newitem.add "age", 41
newitem.add "gender", "Male"

Set newitem = oJSON.AddToCollection(oJSON.data("familyMembers"))
newitem.add "firstName", "Suzan"
newitem.add "age", 38
newitem.add "gender", "Female"

Set newitem = oJSON.AddToCollection(oJSON.data("familyMembers"))
newitem.add "firstName", "John Jr."
newitem.add "age", 11
newitem.add "gender", "Male"

'Return the object
Response.Write oJSON.JSONoutput()
%>
[OUTPUT]

{
  "familyName": "Smith",
  "familyMembers":
  [
    {
      "firstName": "John",
      "age": 41,
      "gender": "Male"
    },
    {
      "firstName": "Suzan",
      "age": 38,
      "gender": "Female"
    },
    {
      "firstName": "John Jr.",
      "age": 11,
      "gender": "Male"
    }
  ]
}

 

 

 

xanburzum como faço pra ler o nó phonenumber??

 

Eu tentei aqui mas não consegui dá erro:

 

Erro de tempo de execução do Microsoft VBScript erro '800a01c2'

Número de argumentos incorreto ou atribuição de propriedade inválida

Compartilhar este post


Link para o post
Compartilhar em outros sites
{
  "api": "sms",
  "codigo": "000",
  "modulo": "recebimentochat",
  "msg": {
    "5564914480001": {
      "5564992251900": [
        {
          "data": "2017-06-28 09:27:03",
          "numDestino": "5564992251900",
          "numOrigem": "5564914480001",
          "textoSms": "Ola MARIA, bom dia e uma mensagem da supera!",
          "tipo": "enviado"
        }
      ],
      "5564992250020": [
        {
          "data": "2017-06-28 09:27:07",
          "numDestino": "5564992250020",
          "numOrigem": "5564914480001",
          "textoSms": "Ola MARIA, bom dia e uma mensagem da supera!",
          "tipo": "enviado"
        }
      ]
    },
    "5564931230001": {
      "5564992251900": [
        {
          "data": "2017-06-28 09:32:56",
          "numDestino": "5564992251900",
          "numOrigem": "5564931230001",
          "textoSms": "MARIA, estamos testando sua mensagem!",
          "tipo": "enviado"
        }
      ],
      "5564992250020": [
        {
          "data": "2017-06-28 09:33:00",
          "numDestino": "5564992250020",
          "numOrigem": "5564931230001",
          "textoSms": "MARIA, estamos testando sua mensagem!",
          "tipo": "enviado"
        }
      ]
    },
    "5564959310010": {
      "5564984085001": [
        {
          "data": "2017-06-28 09:26:52",
          "numDestino": "5564984085001",
          "numOrigem": "5564959310010",
          "textoSms": "Ola, JOAO agradecemos sua visita. Estamos sempre a disposicao, volte sempre!",
          "tipo": "enviado"
        }
      ]
    },
    "5564982870001": {
      "5564992251900": [
        {
          "data": "2017-06-28 09:37:15",
          "numDestino": "5564992251900",
          "numOrigem": "5564982870001",
          "textoSms": "bom dia MARIA estamos fazendo um 3d teste",
          "tipo": "enviado"
        }
      ],
      "5564992250020": [
        {
          "data": "2017-06-28 09:37:19",
          "numDestino": "5564992250020",
          "numOrigem": "5564982870001",
          "textoSms": "bom dia MARIA estamos fazendo um 3d teste",
          "tipo": "enviado"
        }
      ]
    },
    "5564995350010": {
      "5564984085001": [
        {
          "data": "2017-06-28 09:26:21",
          "numDestino": "5564984085001",
          "numOrigem": "5564995350010",
          "textoSms": "Ola, JOAO agradecemos sua visita. Estamos sempre a disposicao, volte sempre!",
          "tipo": "enviado"
        }
      ]
    }
  },
  "status": "ok"
}

Então esse e o meu JSON.

 

Mas eu fiz essa solução e deu certo

 

Set json = New aspJSON
json.loadJSON(respostaJSON)
if json.data("status") = "ok" then
  api = json.data("api")
  set msg = json.data("msg")
  for each origem in msg
    response.write origem
    response.write " | "
    set grupoOrigem = json.data("msg")(origem)
    for each destino in grupoOrigem
      response.write destino
      response.write " { "
      set grupoDestino = json.data("msg")(origem)(destino)
      for each movimentacao in grupoDestino
        set grupoDados = json.data("msg")(origem)(destino)(movimentacao)
        for each dado in grupoDados
            entidade = cint(right(origem, 4))
            response.write vbcrlf
            response.write "entidade: " & entidade
            response.write " | "
            response.write dado
            response.write " : "
            response.write json.data("msg")(origem)(destino)(movimentacao).item(dado)
        next
          response.write vbcrlf
      next
      response.write " } "
      response.write vbcrlf
    next
  next
end if

Funcionou mas achei muito complexo talvez existisse outra saida

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.